我知道在Java中,由于存在擦除操作,因此在运行时没有参数化类型。但是是否有可能在运行时获取那些擦除的参数?让我提供一些示例:
public class MyClass<T>{ };
public static void foo(MyClass<?> p){
//do staff
}
public void main(String[] args){
MyClass<Integer> i = new MyClass<Integer>();
foo(i);
}
现在,我们作为参数传递i
给foo
。是否可以在foo
的体内查询i
实例化了哪种类型的参数?也许某些反射工具可以在运行时保留该信息?
您可以做的另一件事:
private Class<T> type;
public MyClass(Class<T> type) {
this.type = type;
}
public Class<T> getType() {
return type;
}
然后,您将像这样实例化:
MyClass<Integer> i = new MyClass<Integer>(Integer.class);
不是最好的方法,但是它可以解决问题。您可以在foo中访问类型:
p.getType();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句