英文:
Java: conform static class (not instance) to an interface
问题
给定一个示例类:
public final class TestClass {
public static void initialize(final Activity activity, final String myString) {
//这是一个静态方法
}
}
以及一个接口:
public interface IObserver {
void myMethod();
}
我希望这个类本身符合该接口,这样我就会有以下静态方法:
static void myMethod() {
}
并且我将能够将类本身注册为观察者:
anInstanceOfSomeOtherClass.addObserver(this); // 不能编译通过
anInstanceOfSomeOtherClass.addObserver(TestClass); // 我想要这个结果
在Java中是否可能实现这一点,还是我应该重构TestClass
为单例(即只有一个实例)?
注意:传递给addObserver方法的参数是弱引用。
英文:
Given an example class:
public final class TestClass {
public static void initialize(final Activity activity, final String myString) {
//this is a static method
}
}
And an interface:
public interface IObserver {
void myMethod();
}
I'd like the class itself to conform to that interface, so that I'll have the following static method:
static void myMethod() {
}
And so that I'll be able to register the class itself as an observer:
anInstanceOfSomeOtherClass.addObserver(this); // doesn't compile
anInstanceOfSomeOtherClass.addObserver(TestClass); // I want this result
Is this even possible in Java, or should I refactor the TestClass
to be a singleton (i.e. to have a single instance)?
Note: parameter passed to the addObserver method is weakly held.
答案1
得分: 1
如果您正在使用弱引用,那我强烈建议使用单例模式。
原始回答:
如果接口只有一个方法,您可以使用方法引用。
anInstanceOfSomeOtherClass.addObserver(TestClass::myMethod);
如果接口有多个方法,您可以创建一个匿名类:
anInstanceOfSomeOtherClass.addObserver(new IObserver() {
public void myMethod() { TestClass.myMethod(); }
public void anotherMethod() { TestClass.anotherMethod(); }
});
英文:
If you are using weak references, then I strongly suggest a singleton.
<hr>
Original answer:
You could use a method reference if the interface only has one method.
anInstanceOfSomeOtherClass.addObserver(TestClass::myMethod);
If the interface has multiple methods, you can make an anonymous class:
anInstanceOfSomeOtherClass.addObserver(new IObserver() {
public void myMethod() { TestClass.myMethod(); }
public void anotherMethod() { TestClass.anotherMethod(); }
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论