如何获取 接口的泛型
DriverLoginHandler implements BizHandler<LoginParameter>
private Class getParameterClass(BizHandler handler) {
Class handlerClass = handler.getClass();// get from cache
if (cacheClassRaw.get(handlerClass.getName()) != null)
return cacheClassRaw.get(handlerClass.getName());
ParameterizedType pType = null;
/*
* 取接口为 IHandler 的泛型参数类型
*/
for (Type type : handlerClass.getGenericInterfaces()) {
if (type instanceof ParameterizedType) {
ParameterizedType p2 = (ParameterizedType) type;
if (p2.getRawType() == BizHandler.class) {
pType = p2;
break;
}
}
}
/*
* 如果没有取到 IHandler 的泛型参数类型,可能的情况 1 子类没有泛型的IHandler。 比如 SubClass
* implements LogicHandler 2 直接传递IHandler.class 给 getGenericClass 方法
*/
if (pType == null) {
throw new IllegalArgumentException(handlerClass.getName()
+ " must inherit Generic type interface,like implements LogicHandler<T>");
}
Type tp = pType.getActualTypeArguments()[0];
/*
* 如果 泛型参数是一个Class,写缓存 并返回
*/
if (tp instanceof Class) {
// save to cache
cacheClassRaw.put(handlerClass.getName(), (Class) tp);
return (Class) tp;
}
/*
* 如果 泛型参数是一个数组,取数组第一个元素的值
*/
else if (tp instanceof GenericArrayType) {
GenericArrayType arrayType = (GenericArrayType) tp;
Type componentType = arrayType.getGenericComponentType();
Object object = Array.newInstance((Class) componentType, 0);
Class clsClass = object.getClass();
// save to cache
cacheClassRaw.put(handlerClass.getName(), clsClass);
return clsClass;
} else {
throw new IllegalArgumentException(handlerClass.getName()
+ " GenericInterfaces Type is not Class or GenericArrayType type ");
}
}