Java 8:使用反射创建具有泛型的 class 的新实例

Java 8: create new instance of class with generics using reflection

我有以下方法:

public Comparator<T> getComparator()  throws ReflectiveOperationException {
    String className = "some.ClassName";
    Class<Comparator<T>> c = Class.forName(className); // (1)
    return (Comparator<T>) c. newInstance();
}

在第 (1) 行中出现此错误:

Type mismatch: cannot convert from Class <capture#1-of ?> to Class<Comparator<T>>

这段代码有什么问题,我应该如何创建 Comparator<T> 的实例?

只需移动演员表:

Class<Comparator<T>> c = (Class<Comparator<T>>) Class.forName(className); // (1)
return c.newInstance();

试试这个解决方案

@SuppressWarnings("unchecked")
public Comparator<T> getComparator() throws Exception {
    String className = "some.ClassName";
    Class<?> c = Class.forName(className); // (1)
    return (Comparator<T>) c. newInstance();
}

到目前为止你能得到的最好的是

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;
}

请注意,仍然存在无法避免的未经检查的操作。运行时类型令牌 Comparator.class 生成 Class<Comparator> 而不是 Class<Comparator<T>>,它反映了类型擦除并暗示您可以通过 asSubclass 使用它来确保 Class确实实现了 Comparator,但您不能确保它实现了关于任何 <T>Comparator<T>。 (请注意,此方法甚至不知道 T 是什么)。因此,仍然存在 ComparatorComparator<T>.

的未经检查的转换