假设我有一些 Java 类实现 List<T>
叫Foo
将其扩展为 String
,如何获取 List
的类型变量(本例中是 String
)? [只是在我自己实现之前知道,P.S.我确信 springframework 可以做到这一点]
注意,可以这样做,因为 Foo
类元数据包含通用父类(super class)和接口(interface),与想要了解 new LinkedList<String>()
内部的类型不同。
注意使用 ((ParameterizedType)Foo.class.getGenericSuperClass()).getActualTypeArguments()[0]
不足以满足我的需求(请参阅下面的代码: Foo
和 Bar
)
显示我想要的代码:
// 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))
实现需要遍历所有类层次结构并使用 ParameterizedType 和 TypeVariable 接口(interface)以及其他一些人员。
但是这个问题是题外话,因为我问什么库实现了这个(参见 https://stackoverflow.com/help/on-topic )
最佳答案
您可以使用我的实用程序GenericUtil
,查看它 here .
使用以下方法
public static Type[] getGenericTypes(Type sourceType, Class<?> targetClass)
它可以推断任何泛型类型,即使它不是显式的。
在你的情况下你可以这样做
getGenericTypes(Foo.class, List.class) // {String.class}
getGenericTypes(Bar.class, List.class) // {Long.class}
getGenericTypes(Bar.class, TypeList.class) // {Integer.class, Long.class}
即使你也能做到
interface Baz<T> extends TypeList<T, Long> {}
getGenericTypes(Baz.class, List.class) // {Long.class}
getGenericTypes(Baz.class, TypeList.class) // {T, Long.class}
关于java - 从实现类中获取类型参数的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43922989/