Java泛型反射:子类的泛型字段类型 [英] Java Generics Reflection: Generic field type of subclass
本文介绍了Java泛型反射:子类的泛型字段类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
class Example1< A,B> {
公共地图< A,B> someMap = new HashMap< A,B>();
}
class Example2 extends Example1< URL,URL> {
}
有什么方法可以使用反射我可以确定示例2的映射的组件类型?
我知道我可以这样做:
ParameterizedType t =(ParameterizedType )Example2.class.getFields()[0] .getGenericType();
但是从那里,我似乎无法弄清楚这两个组件是URL。 p>
有没有人有任何想法?解决方案
以下将打印出您想要的内容:
ParameterizedType superClass =(ParameterizedType)Example2.class.getGenericSuperclass();
System.out.println(superClass.getActualTypeArguments()[0]);
System.out.println(superClass.getActualTypeArguments()[1]);
打印出来:
class java.net.URL
class java.net.URL
Given two classes like this:
class Example1<A,B> {
public Map<A,B> someMap = new HashMap<A,B>();
}
class Example2 extends Example1<URL, URL> {
}
Is there any way using reflection that I can determine the component types of the Map for Example2?
I know I can do:
ParameterizedType t = (ParameterizedType) Example2.class.getFields()[0].getGenericType();
But from there, I can't seem to figure out that the two components are URLs.
Does anyone have any ideas?
解决方案
Darron is not completely correct. The following will print out what you want:
ParameterizedType superClass = (ParameterizedType) Example2.class.getGenericSuperclass();
System.out.println(superClass.getActualTypeArguments()[0]);
System.out.println(superClass.getActualTypeArguments()[1]);
Prints out:
class java.net.URL
class java.net.URL
这篇关于Java泛型反射:子类的泛型字段类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文