使用另一个类的字段类型实例化参数化类
我想使用从类字段(使用反射)获取的类型来实例化带有泛型的类。
注意:为了便于阅读,我省略了例外情况。
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>();
}
}
我想要达到的目标合理吗?关于如何解决这个问题有什么想法吗?
谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
无论您尝试做什么都是不合理的,因为如果您查看以下行:
typeClass
是编译器应该注意的事情。但在你的情况下,它只能在运行时通过反射知道。编译器需要删除
BClass
中的T
并将其替换为具体类型,在您的情况下,该类型在编译时未知,因此逻辑上它是无效的。Whatever you are trying to do is not reasonable because if you look at the following line:
typeClass
is something that compiler should be aware of. But in your case it's only known in the runtime through reflection.Compiler needs to erase
T
inBClass<T>
and replace it with a concrete type which in your case is unknown at compile time so logically it's invalid.您可以捕获 typeClass 类型的类型参数:
You can capture the type argument of the type of typeClass: