Search code examples
javastaticdelegatesstatic-methodsobserver-pattern

Java: conform static class (not instance) to an interface


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.


Solution

  • If you are using weak references, then I strongly suggest a singleton.


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