- /**
- * Create a new instance which will try to detect the types to match out of the type parameter of the class.
- *
- * @param autoRelease {@code true} if handled messages should be released automatically by pass them to
- * {@link ReferenceCountUtil#release(Object)}.
- */
- protected SimpleChannelInboundHandler(boolean autoRelease) {
- // 根据传入的泛型来确定类型拦截器
- matcher = TypeParameterMatcher.find(this, SimpleChannelInboundHandler.class, "I");
- this.autoRelease = autoRelease;
- }
直觉又感觉不对,做了个代码试验确实不行,只是表示个字符串“I“,没有别的功能。
那代码中又如何实现来确定泛型类型的呢,进一步研究源代码发现其最终实现是在TypeParameterMatcher.find0中
TypeParameterMatcher matcher = map.get(typeParamName);
if (matcher == null) {
matcher = get(find0(object, parameterizedSuperclass, typeParamName));
map.put(typeParamName, matcher);
}
private static Class<?> find0(
final Object object, Class<?> parameterizedSuperclass, String typeParamName) {
TypeVariable<?>[] typeParams = currentClass.getSuperclass().getTypeParameters();
System.out.println("find0 typeParams num:"+typeParams.length);
for (int i = 0; i < typeParams.length; i ++) {
System.out.println("find0 typeParamName:"+typeParamName+"typeParams["+i+"].getName():"+typeParams[i].getName());
if (typeParamName.equals(typeParams[i].getName())) {
typeParamIndex = i;
break;
}
}
if (typeParamIndex < 0) {
throw new IllegalStateException(
"unknown type parameter '" + typeParamName + "': " + parameterizedSuperclass);
}
Type genericSuperType = currentClass.getGenericSuperclass();
System.out.println("find0 genericSuperType:"+genericSuperType.getTypeName());
if (!(genericSuperType instanceof ParameterizedType)) {
return Object.class;
}
Type[] actualTypeParams = ((ParameterizedType) genericSuperType).getActualTypeArguments();
Type actualTypeParam = actualTypeParams[typeParamIndex];
System.out.println("find0 actualTypeParam:"+actualTypeParam.getTypeName());
if (actualTypeParam instanceof ParameterizedType) {
actualTypeParam = ((ParameterizedType) actualTypeParam).getRawType();
}
if (actualTypeParam instanceof Class) {
System.out.println("find0 actualTypeParam:"+actualTypeParam.getTypeName());
return (Class<?>) actualTypeParam;
}
}
相关阅读:
http://stackoverflow.com/questions/27083667/proguard-and-netty-5-on-android