我想使用从类'字段(使用反射)获取的类型来实例化具有泛型的类。
注意:我省略了希望易于阅读的例外情况。
public class AClass {
class BClass<T> {
T aMemba;
}
public void AMethod() {
Class c = Class.forName("com.bla.flipper");
Field f = c.getField("flipIt");
// Here is my difficulty, I want to instantiate BClass with the type of
// field 'f' but the compiler won't let me.
Class typeClass = f.getType();
BClass<typeClass> = new BClass<typeClass>();
}
}
我想要实现合理吗?有关如何解决这个问题的想法吗?
谢谢!
答案 0 :(得分:2)
无论你想做什么都是不合理的,因为如果你看下面一行:
BClass<typeClass> = new BClass<typeClass>();
typeClass
是编译器应该注意的事情。但在你的情况下,它只在运行时通过反射知道。
编译器需要擦除T
中的BClass<T>
并将其替换为具体类型,在编译时这种情况在您的情况下是未知的,因此逻辑上它是无效的。
答案 1 :(得分:1)
您可以捕获typeClass类型的类型参数:
Field f = ...;
Class<?> typeClass = f.getType();
withClassCapture(typeClass);
private <T> void withClassCapture(Class<T> klazz) {
BClass<T> instance = new BClass<T>();
// ... do your thing
}