jeudi 11 mai 2017

Getting Class of type parameter from implementing class

Lets say I have some class in Java that implements List<T> called Foo that extends it with String, Is there a library that can return 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

Code that shows what I want:

// java.util: interface List<T> { }

interface TypeList<A, T> extends List<T> { }

class interface Foo extends List<String> { }

public 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))





Aucun commentaire:

Enregistrer un commentaire