geejay
geejay

Reputation: 5618

Check if field type is same as generic type in java

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

Upvotes: 4

Views: 864

Answers (1)

Bozho
Bozho

Reputation: 597382

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

Upvotes: 4

Related Questions