java如何从实现接口的泛型类返回接口?
我想创建一个方法,它接受实现任何接口的任何类T
然后对该类执行一些操作,并返回实现的接口I
以下是我尝试过的:
class MyLibrary {
public static <I, T extends I> I registerImplementation(Class<T> classImpl) {
I interfaceImpl = (I) classImpl.newInstance();
return interfaceImpl;
}
}
然后我创建一个接口和一个实现该接口的类:
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");
}
}
然而,当我调用引用UserClass
的方法时,它返回相同的类类型T
,而不是接口类型I
,允许调用接口中未声明的所有类方法
也就是说,在下面的语句中,即使registerImplementation()
被声明为返回对UserInterface
的引用,编译器仍将引用视为指向UserClass_v1_10_R2
的实例,允许访问接口中不存在的实现方法
MyLibrary.registerImplementation(UserClass_v1_10_R2.class).doVersionSpecificStuff();
将此与假定相同的情况进行对比
UserInterface uiObj = MyLibrary.registerImplementation(UserClass_v1_10_R2.class);
uiObj.doVersionSpecificStuff(); // This does not compile
共 (0) 个答案