Check if field type is same as generic type in java

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

For instance,

Foo extends Bar<Foo> Foo x; 

How to determine if field x is entered as a subtype of Bar<Foo> ?

+4
source share
1 answer
 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 check if it is Foo or not.

i.e.

 if (types[0] instanceof Class) { if (x.getClass().isAssignebleFrom(((Class) type[0]))){ // do something } } 
+4
source

Source: https://habr.com/ru/post/1308662/


All Articles