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!
This is not possible due to Java’s type erasure. When compiled, the generic types will be replaced by raw types, resulting in something like this:
The actual types are then filled in places where you are directly working with
foo1andfoo2. For example, the following code:will be translated to something like:
Long story short: there’s no way you can retrieve that type, since it is discarded at compile time.