Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generics and Class.asSubclass

I've always thought the following should work. I get an object which I know is a Class<X> where X extends some class Xyz. In order to make it type-safe I wanted to use Class.asSubclass like in the following method:

private Class<? extends Xyz> castToXyzClass(Object o) {
    final Class<?> resultClass = (Class<?>) o;
    final Class<? extends Xyz> result = Xyz.class.asSubclass(resultClass);
    return result;
}

However, in Eclipse it doesn't work, the only solution I see is an unchecked cast. I'd bet the above code must work, I've used something like this already... no idea what's wrong here.

like image 452
maaartinus Avatar asked May 09 '11 16:05

maaartinus


1 Answers

asSubclass() operates on the object it's called on, not on its parameter - not what one is used to, but it reads quite well. You just have to do this:

final Class<? extends Xyz> result = resultClass.asSubclass(Xyz.class);
like image 147
Michael Borgwardt Avatar answered Sep 20 '22 05:09

Michael Borgwardt