简体   繁体   中英

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:

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

What's wrong in this code and how should I make an instance of 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> . (Note that this method doesn't even know what T is). Therefore there is still an unchecked conversion of Comparator to 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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM