Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to cast a class to have specific parameters to the java.lang.Class<> generic?

Tags:

java

generics

Class<? extends MyClass> cls = (Class<? extends MyClass>) Class.forName(className);
someMethod(cls); // someMethod expects a Class<? extends MyClass>

The above statement gives a warning "Type safety: Unchecked cast from Class<capture#5-of ?> to Class<? extends MyClass>".

Class<?> cls0 = Class.forName(className);
if (cls0 instanceof Class<? extends MyClass>) {
    Class<? extends MyClass> cls = (Class<? extends MyClass>)cls0;
    someMethod(cls);
}

This time I get an error, because of type erasure...

Class<?> cls0 = Class.forName(className);
if (MyClass.class.isAssignableFrom(cls0)) {
    Class<? extends MyClass> cls = (Class<? extends MyClass>)cls0;
    someMethod(cls);
}

This time I know that the cast is safe, but the compiler doesn't, and still gives the warning. (If you ask me, the compiler is being a bit thick here.)

Is there any way to avoid this warning (except for SuppressWarnings)?

like image 501
Adam Burley Avatar asked Sep 28 '22 19:09

Adam Burley


1 Answers

The correct way to do what you want is:

Class.forName(className).asSubclass(MyClass.class);
like image 166
jtahlborn Avatar answered Oct 13 '22 22:10

jtahlborn