想象一下,你有这样的情况:Java的泛型返回动态类型
// Marker
interface Type {}
interface CustomType extends Type {
int getSomething();
int getAnotherThing();
}
class CustomTypeImpl implements CustomType {
public int getSomething() {
return 1;
}
public int getAnotherThing() {
return 2;
}
}
在另一类,我想有这样一个通用的方法:
public <T extends CustomType> T getFromInterface(Class<T> clazz)
返回的实现我输入参数。例如,我想调用如下的方法:SomeInstanceOfClass.getFromInterface(CustomType.class)
,它返回一个CustomTypeImpl
的实例。
@ EDIT:我忘了提及我有权访问一个方法,该方法存储所有可用作方法参数的接口。
此方法的签名是:public Set<? extends Class<? extends Type>> allTypes()
如何管理做到这一点吗?
如果接口有两个实现呢?如果它从来不这样做,那么接口的意义何在? –
实际上,我有一个标记接口,允许我的对象具有通用类型。情况就像这样:interface Type {// marker} interface CustomType extends Type {// look above}和我的实现。实际上,我有扩展Type的其他接口,然后我为每个扩展Type的接口实现了一个实现。 –
答案可能会解决您的问题,但我认为无论您的问题是什么,都可能有更好的解决方案。 –