Narendra Pathai
Narendra Pathai

Reputation: 41975

Getting rid of unchecked cast in reflection

I am loading a class using classloader which returns me Class<?> and now I want to pass the class to another method or function that takes Class<? extends SomeClass>.

Now when I try to cast:

Class<?> clazzFromClassLoader = Class.forName(nameOfClass);
Class<? extends Someclass> clazz = (Class<? extends SomeClass>)clazzFromClassLoader;
//second line gives unchecked cast warning

I can make sure that there is no class cast exception by using

SomeClass.isAssignableFrom(clazzFromClassLoader);

But is there a way to get rid of unchecked cast?

Upvotes: 3

Views: 719

Answers (1)

ruakh
ruakh

Reputation: 183504

Yes: you can write:

Class<? extends Someclass> clazz =
    clazzFromClassLoader.asSubclass(Someclass.class);

(See asSubclass's Javadoc for more information.)

Upvotes: 10

Related Questions