Consider the following Java code:
public class Test
{
private Foo< String, String > foo1;
private Foo< Integer, Integer > foo2;
}
public class Foo< T, V >
{
private Bar< V > bar;
private T a;
}
public class Bar< T >
{
@MyAnnotation
private List< T > list;
}
First, starting with the class named 'Test', I'm searching all fields recursively, which are annotated with 'MyAnnotation' and whose type is derived from 'java.lang.Collection'. For the given example, the results would be:
It's obviosly clear, that the first one can only take strings for its elements, whereas the second one can only take integers.
My Question is: What is the best (easiest) way to find all Collection fields annotated with 'MyAnnotation' and tell their element type?
Finding annotated fields from type java.lang.Collection is not the problem. But how can we get a result which looks like the following one for the given example?
I've tried several approaches, which always gave me 'Object' as the collection's element type instead of 'String'.
I'm really stuck on this. Many thanks in advance!
May be you can try like this:
Field field = Test1.class.getField("list");
Type genericFieldType = field.getGenericType();
if(genericFieldType instanceof ParameterizedType){
ParameterizedType aType = (ParameterizedType) genericFieldType;
Type[] fieldArgTypes = aType.getActualTypeArguments();
for(Type fieldArgType : fieldArgTypes){
Class fieldArgClass = (Class) fieldArgType;
System.out.println("fieldArgClass = " + fieldArgClass);
}
}
This will return fieldArgClass = java.lang.String
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With