开发者

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 subt开发者_JS百科ype of Bar<Foo>?


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜