[英]Instantiate parameterized class using a field type of another class
I would like to use a type which I get from a class' field (using reflection) to instantiate a class with generics. 我想使用从类的字段中获取的类型(使用反射)来实例化具有泛型的类。
Note: I omitted the exceptions hoping for easy reading. 注意:我省略了希望易于阅读的例外情况。
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>();
}
}
Is what I want to achieve reasonable? 我想实现的目标合理吗? Any thought on how I can solve this problem? 有关如何解决这个问题的想法?
Thanks! 谢谢!
Whatever you are trying to do is not reasonable because if you look at the following line: 无论你想做什么都是不合理的,因为如果你看下面一行:
BClass<typeClass> = new BClass<typeClass>();
typeClass
is something that compiler should be aware of. typeClass
是编译器应注意的事情。 But in your case it's only known in the runtime through reflection. 但在你的情况下,它只在运行时通过反射知道。
Compiler needs to erase T
in BClass<T>
and replace it with a concrete type which in your case is unknown at compile time so logically it's invalid. 编译器需要擦除T
的BClass<T>
并用一个具体类型而你的情况是未知的编译时间,以便在逻辑上是无效的更换。
You can capture the type argument of the type of typeClass: 您可以捕获typeClass类型的type参数:
Field f = ...;
Class<?> typeClass = f.getType();
withClassCapture(typeClass);
private <T> void withClassCapture(Class<T> klazz) {
BClass<T> instance = new BClass<T>();
// ... do your thing
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.