Java:使静态类(而不是实例)符合某个接口

huangapple go评论57阅读模式
英文:

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(); }
});

huangapple
  • 本文由 发表于 2020年9月23日 18:39:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/64026134.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定