java 泛型应用1:获取接口泛型定义

如何获取 接口的泛型

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 ");
}


    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值