[英]Java instantiate class of parameterized type
Here's what I have: 这是我所拥有的:
class Class1 <T>
{
public void foo()
{
ParameterizedType parameterizedType = (ParameterizedType)getClass().getGenericSuperclass();
Class<T> type = (Class<T>) parameterizedType.getActualTypeArguments()[0];
System.out.println(type);
}
}
class Class2 <G>
{
public Class2 ()
{
Class1<G> class1 = new Class1<G>();
}
}
But when I call class1.foo(), I get the superclass and not the parameter. 但是,当我调用class1.foo()时,我得到的是超类而不是参数。
If I do 如果我做
Class1<String> class1 = new Class1<String>();
and then call class1.foo() inside Class1, I get String. 然后在Class1内调用class1.foo(),我得到了String。
How can I fix to instantiate Class1 with the generic type of Class2? 如何解决使用Class2的通用类型实例化Class1的问题?
You cannot. 你不能。 At runtime, Class2
doesn't know what its generic type argument is. 在运行时, Class2
不知道其通用类型参数是什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.