在项目中写一个class时如果实现了一个泛型接口,如Map<S, T> 可以通过以下代码取出实现的泛型接口的具体类型,摘自spring源代码GenericTypeResolver
/**
* 取类classToIntrospect实现的类genericIfc的泛型类信息
* @param ownerClass 当前类的class,
* @param classToIntrospect 查询类classToIntrospect的泛型的具体实现
* @param genericIfc 实现的泛型接口
* @return
*/
private static Class[] doResolveTypeArguments(Class ownerClass, Class classToIntrospect, Class genericIfc) {
while (classToIntrospect != null) {
if (genericIfc.isInterface()) {
//取classToIntrospect 实现的泛型接口的类型信息
Type[] ifcs = classToIntrospect.getGenericInterfaces();
for (Type ifc : ifcs) {
Class[] results = doResolveTypeArguments(ownerClass, ifc, genericIfc);
if (results != null) {
return results;
}
}
} else {
//class.getGenericSuperclass()所有实现的泛型接口
//Converter<String, Boolean>
Class[] results = doResolveTypeArguments(ownerClass, classToIntrospect.getGenericSuperclass(), genericIfc);
if (results != null) {
return results;
}
}
classToIntrospect = classToIntrospect.getSuperclass();
}
return null;
}
private static Class[] doResolveTypeArguments(Class ownerClass, Type ifc, Class genericIfc) {
if (ifc instanceof ParameterizedType) {
ParameterizedType paramIfc = (ParameterizedType)ifc;
Type rawType = paramIfc.getRawType();
if (genericIfc.equals(rawType)) {
Type[] typeArgs = paramIfc.getActualTypeArguments();
Class[] results = new Class[typeArgs.length];
for (int i = 0; i < typeArgs.length; i++) {
Type arg = typeArgs[i];
results[i] = extractClass(ownerClass, arg);
}
return results;
} else if (genericIfc.isAssignableFrom((Class)rawType)) {
return doResolveTypeArguments(ownerClass, (Class)rawType, genericIfc);
}
} else if (ifc != null && genericIfc.isAssignableFrom((Class)ifc)) {
return doResolveTypeArguments(ownerClass, (Class)ifc, genericIfc);
}
return null;
}
测试例子
@Test
public void testGenericType() {
StringToBoolean params = new StringToBoolean();
Class[] genericArgs = GenericTypeResolver.resolveTypeArguments(params.getClass(), Converter.class);
Assert.assertEquals(String.class, genericArgs[0]);
Assert.assertEquals(Boolean.class, genericArgs[1]);
}
interface Converter<S, T> {
}
class StringToBoolean implements Converter<String, Boolean> {
}