Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Java Reflections to find Collection's element type?

Tags:

java

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:

  • Test.foo1.bar.list
  • Test.foo2.bar.list

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?

  • Test.foo1.bar.list< String >
  • Test.foo2.bar.list< Integer >

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!

like image 462
theV0ID Avatar asked Dec 20 '22 20:12

theV0ID


1 Answers

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

like image 161
UVM Avatar answered Jan 23 '23 17:01

UVM