请注意:这里的示例基于InvocationHandler实例,实际上是来自mybatis-3的MapperProxy实例
如下所示:
public interface A<T1,T2> {}
public interface B<T4,T3> extends A<T3,T4> {}
public class C implements B<Long, String> {}如何检索接口T2的实际类型A?
((ParameterizedType)((Class)((ParameterizedType)((Class)this.getClass()
.getGenericInterfaces()[0]).getGenericInterfaces()[0]).getRawType())
.getGenericInterfaces()[0]).getActualTypeArguments()`将只返回[P,E],但是,[String, Long]才是我真正想要检索的。
当然,这里我们可以从以下站点获得实际的参数化类型:
((ParameterizedType)((Class)this.getClass().getGenericInterfaces()[0])
.getGenericInterfaces()[0]).getActualTypeArguments()例如,在这里我可以得到[Long, String]。
但是,如果参数化的B类型有不同的序列,而且我不知道区别是什么,我如何才能得到实际的A类型?
发布于 2016-12-01 09:26:05
好的,经过长时间的思考和测试,这个问题的解决方案即将到来。
该解决方案最重要的思想是将B**'s类型参数作为** A的类型参数传递
解决这个问题有几个关键点:
B的类型参数和类型参数的类型映射;A的类型参数;A类型参数检索实际类型参数;关于前一个例子的详细内容:
B.class.getTypeParameters() => [T4,T3]B.class.getActualTypeArguments() => [Long,String]A.class.getTypeParameters() => [T1,T2]A.class.getActualTypeArguments() => [T3,T4]A.parameterizedType[T1] <= B.typeArguments[T3] <= String在重复这样做之后,可以正确地得到实际的类型参数。
https://stackoverflow.com/questions/40884235
复制相似问题