views:

66

answers:

1

I want to determine if a field is typed as the subclass of a generic type.

For e.g

Foo extends Bar<Foo>

Foo x;

How do I tell if the field x is typed as a subtype of Bar<Foo>?

+3  A: 
Type genericSuperclass = x.getClass().getGenericSuperclass();
if (genericSuperclass instanceof ParameterizedType) {
    Type[] types = 
       ((ParameterizedType) genericSuperclass).getActualTypeArguments();
}

Then you can use Class.isAssignableFrom, if type instanceof Class, to verify whether it is Foo or not.

i.e.

if (types[0] instanceof Class) {
    if (x.getClass().isAssignebleFrom(((Class) type[0]))){
        // do something
    }
}
Bozho
What is `ParameterizedType`? You can't use generic type parameters (the typical `K`, `V`, `E`, `T`) in `instanceof`, can't you?
polygenelubricants
`ParameterizedType` represents (in this case) the following information: `Bar<Foo>` - i.e. (as far as I understood) - what geejay needs to know.
Bozho
Thanks but how do I use this to determine if it is a subtype (of Bar that is)?
geejay
@Bozho: wouldn't this be analogous to doing `aList instanceof List<String>`? Which you can't do in Java?
polygenelubricants
No, java.lang.reflect.ParameterizedType is something that can be retrieved by reflection from the superclass of a class, and it contains the actual type information for that superclass.
ColinD
@ColinD, @Bozho: Fascinating stuff. This is the first time I've seen `java.lang.reflect.Type`.
polygenelubricants
@geejay - as I said, using `isAssignableFrom`. see my update.
Bozho
I think I have a better solution. Simply Bar.class.isAssignableFrom(x.getClass())
geejay
well, of course, in case you know the class beforehand. I thought you want something dynamic.
Bozho
That'll tell you if you have an instance of `Bar` (you could also do `x instanceof Bar` if that's all you want) but not whether that `Bar`'s type argument is `Foo`.
ColinD
Sorry peoples. I think I confused everyone here, nonetheless the solution given is still handy. Thanks all.
geejay