[英]Using generic as method parameter
I have a problem when using generic types. 使用泛型类型时遇到问题。 IDE show me following error:
IDE显示以下错误:
Cannot select from a type variable
I think here problem with type erasure, but I think here exist some workaround... 我认为这里有类型擦除的问题,但我认为这里存在一些解决方法......
My code: 我的代码:
class MyFactory {
public Object getByClass(Class<?> clazz) {
.....
}
}
class<T> MyClass {
private Object myObj = MyFactory.getByClass(T.class); // HERE ERROR, `Cannot select from a type variable`
...
}
How to solve this problem? 如何解决这个问题呢?
Pass the Class
object into the constructor. 将
Class
对象传递给构造函数。
private final Class<T> clazz;
private Object myObj
public MyClass(Class<T> clazz, MyFactory myFactory) {
this.clazz = clazz;
this.myObj = myFactory.getByClass(clazz);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.