2020-11-29

How to return interface from generic class implementing the interface?

I want to make a method that accepts any class (T) that implements any interface (I), do something with the class and return the interface (I) that it implements. Here's what I've tried:

class MyLibrary {
    
    public static <I, T extends I> I registerImplementation(Class<T> classImpl) {
        I interfaceImpl = (I) classImpl.newInstance();
        return interfaceImpl;
    }
}

I'm then creating an interface and a class which implements that interface:

interface UserInterface {
    void doSomethingDefined();
}

class UserClass_v1_10_R2 implements UserInterface {

    @Override
    public void doSomethingDefined() {
        System.out.println("What this does is well-defined");
    }

    public void doVersionSpecificStuff() {
        System.out.println("This is not in the interface, so don't really depend on this");
    }
}

However, when I'm calling the method referencing UserClass, it returns the same class type (T) instead of the interface type (I), allowing all the class methods which are not declared in the interface to be called.

I.e. in the statement below, even though registerImplementation() is declared to return a reference to UserInterface, the compiler sees the reference as pointing to an instance of UserClass_v1_10_R2, allowing access to the implementation's methods that are not in the interface.

MyLibrary.registerImplementation(UserClass_v1_10_R2.class).doVersionSpecificStuff();

Contrast this with the supposedly identical

UserInterface uiObj = MyLibrary.registerImplementation(UserClass_v1_10_R2.class);
uiObj.doVersionSpecificStuff(); // This does not compile


from Recent Questions - Stack Overflow https://ift.tt/3lf8aSU
https://ift.tt/eA8V8J

No comments:

Post a Comment