获取具有反射的特定参数化类型



我知道我可以通过以下方式获得类的参数化类型:

Type[] genericInterfaces = getClass().getGenericInterfaces();
for (Type genericInterface : genericInterfaces) {
if (genericInterface instanceof ParameterizedType) {
ParameterizedType type = (ParameterizedType) genericInterface;
// do something 
}
}

但假设我需要检查一个特定的参数化类型,比如List<T>type提供getRawType().getTypeName(),我可以将其与List的类名(或简单类名,我不确定(进行比较。这是正确的路吗?

更新:

更具体地说:如何让所有bean实现一个特定的接口,然后将映射上的泛型类型参数注册为键,将bean注册为值。

只有当List<T>是直接接口并且T是显式的时,您的方法才有效。

你可以使用我的实用程序类GenericUtil

// your approach only works for this situation
class Foo implements List<String>{}
// your approach not work in these situations
class A<T> implements List<T>{}
class B extends A<Integer>{}
class C extends A<A<C>>{}
GenericUtil.getGenericTypes(Foo.class, List.class); // {String}
GenericUtil.getGenericTypes(A.class, List.class); // {T}
GenericUtil.getGenericTypes(B.class, List.class); // {Integer.class}
GenericUtil.getGenericTypes(C.class, List.class); // {A<C>}

最新更新