[英]Java 8: create new instance of class with generics using reflection
I have the following method: 我有以下方法:
public Comparator<T> getComparator() throws ReflectiveOperationException {
String className = "some.ClassName";
Class<Comparator<T>> c = Class.forName(className); // (1)
return (Comparator<T>) c. newInstance();
}
In the line (1) I get this error: 在第(1)行中,出现此错误:
Type mismatch: cannot convert from Class <capture#1-of ?> to Class<Comparator<T>>
类型不匹配:无法从类别<capture#1-of?>转换为Class <Comparator <T >>
What's wrong in this code and how should I make an instance of Comparator<T>
? 这段代码有什么问题,我应该如何创建
Comparator<T>
的实例?
The best you can get so far is 到目前为止你能得到的最好的是
public <T> Comparator<T> getComparator() throws ReflectiveOperationException {
Class<? extends Comparator> implementation
= Class.forName("some.ClassName").asSubclass(Comparator.class);
@SuppressWarnings("unchecked")
final Comparator<T> c = implementation.newInstance();
return c;
}
Note that there is still an unchecked operation which is unavoidable. 请注意,仍然存在无法避免的未经检查的操作。 The runtime type token
Comparator.class
produces a Class<Comparator>
rather than Class<Comparator<T>>
which reflects the type erasure and implies that you can use it via asSubclass
to ensure that a Class
indeed implements Comparator
, but you can't ensure that it implements Comparator<T>
regarding any <T>
. 运行时类型令牌
Comparator.class
生成Class<Comparator>
而不是Class<Comparator<T>>
,这反映了类型擦除,并暗示您可以通过asSubclass
使用它来确保Class
确实实现Comparator
,但是您不能确保对任何<T>
实现Comparator<T>
<T>
。 (Note that this method doesn't even know what T
is). (请注意,此方法甚至都不知道
T
是什么)。 Therefore there is still an unchecked conversion of Comparator
to Comparator<T>
. 因此,仍然存在未经检查的
Comparator
到Comparator<T>
转换。
Simply move the cast: 只需移动演员:
Class<Comparator<T>> c = (Class<Comparator<T>>) Class.forName(className); // (1)
return c.newInstance();
Try this solution 试试这个解决方案
@SuppressWarnings("unchecked")
public Comparator<T> getComparator() throws Exception {
String className = "some.ClassName";
Class<?> c = Class.forName(className); // (1)
return (Comparator<T>) c. newInstance();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.