Lets say I have some class in Java that implements List<T>
called Foo
that extends it with String
, how can I get the type variable of the List
(which is in this example is String
)? [Just to know before I go and implement this myself, P.S. I am sure that springframework can do this]
NOTICE that this could be done because Foo
class metadata contains the generic super class and interfaces and not the same as wanting to know the type inside new LinkedList<String>()
NOTICE that using ((ParameterizedType)Foo.class.getGenericSuperClass()).getActualTypeArguments()[0]
is not good enough for my needs(see the code below: Foo
and Bar
)
Code that shows what I want:
// java.util: interface List<T> { }
interface TypeList<A, T> extends List<T> { }
interface Foo extends List<String> { }
interface Bar extends TypeList<Integer, Long> { }
Class<?> getTypeParameter(Class<?> fromClass, Class<?> superTypeWithTypeVariables, int indexOfTypeVariable) {
// ...
}
// Foo -> List<String> -> List<E> -> E is #0
assertEquals(String.class, getTypeParameter(Foo.class, List.class, 0))
// Bar -> TypeList<..., Long> -> TypeList<..., T> -> List<T> -> List<E> -> E is #0
assertEquals(Long.class, getTypeParameter(Bar.class, List.class, 0))
The implementation needs to go over all the class hierarchy and use ParameterizedType and TypeVariable interfaces, and some other staff.
But this question is off-topic because I asked what library implements this(see https://stackoverflow.com/help/on-topic)