2

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>?

3 Answers 3

4

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>.

Sign up to request clarification or add additional context in comments.

Comments

0

Simply move the cast:

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

4 Comments

It will work, but it's a java2-style approach. I was looking for java5-style one.
Also, it generates warning: Type safety: Unchecked cast from Class<capture#1-of ?> to Class<Comparator<T>>
@Antonio, what do you mean by "java5-style". Class.forName() will return a Class<?> object and you will need to cast it to whatever you want and make sure the casting will work fine... Because compiler cannot make sure the string "some.ClassName" is the name of a class implementing Comparator<T>.
@Antonio Do you mean something like String className = "some.ClassName"; Class<?> aClass = Class.forName(className); Object obj = aClass.newInstance(); return Comparator.class.cast(obj);
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.