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
}
}
精彩评论