开发者

Check if field type is same as generic type in java

开发者 https://www.devze.com 2022-12-29 13:47 出处:网络
I want to determine if a field is typed as the subclass of a generic type. For e.g Foo extends Bar<Foo>

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

精彩评论

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