[英]Java Generic return dynamic type
想象一下您有一个这样的情况:
// 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 :我忘了提到我可以访问一种方法,该方法存储所有可用作getFromInterface(Class<T> clazz)
方法的参数的接口。
此方法的签名是: public Set<? extends Class<? extends Type>> allTypes()
public Set<? extends Class<? extends Type>> allTypes()
我如何设法做到这一点?
您可以使用反射并使用类对象创建新实例。 有关什么类实现某些接口的信息可以存储在某些映射中。
private static final Map<Class<?>, Class<?>> interfaceToImplementationMap = new HashMap<Class<?>, Class<?>>() {{
put(CustomType.class, CustomTypeImpl.class);
}};
public static void main(String[] args) throws InstantiationException, IllegalAccessException {
CustomType instance = getFromInterface(CustomType.class);
System.out.println(instance);
}
public static <T> T getFromInterface(Class<T> clazz) throws IllegalAccessException, InstantiationException {
return clazz.cast(interfaceToImplementationMap.get(clazz).newInstance());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.