use*_*116 0 java generics reflection introspection propertydescriptor
说我有一个豆子
public class SomeBean{
List<String> messages;
List<Integer> scores;
String id;
int number;
Run Code Online (Sandbox Code Playgroud)
....}
我使用以下代码来处理或转储propreties
BeanInfo beanInfo = Introspector.getBeanInfo(beanClass, Object.class);
PropertyDescriptor descriptors[] = beanInfo.getPropertyDescriptors();
int stop = descriptors.length;
for (int i = 0; i < stop; ++i) {
PropertyDescriptor descriptor = descriptors[i];
logger.info(descriptor.getName() + " : " + descriptor.getPropertyType().getName() + ", writemethod :" + descriptor.getWriteMethod());
}
Run Code Online (Sandbox Code Playgroud)
我希望能够获得"分数"和"消息"的参数化类型.当我破坏代码时,"descriptor.getPropertyType().getName()"的值对于消息和分数都是"java.util.List".
如何判断"消息"的属性描述符是否指的List<String>是"分数"是指List<Integer>?
有两种情况.
第一种情况是在编译时不知道属性的参数化类型:
public class Pair<A, B> {
public A getFirst() { ... }
public B getSecond() { ... }
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,您无法在编译时知道,并且是@darioo正在谈论的内容.
第二种情况是你的,当属性的类型参数在运行时已知.下面的代码可以帮助您确切了解您想要做的事情:
BeanInfo beanInfo = Introspector.getBeanInfo(beanClass, Object.class);
PropertyDescriptor descriptors[] = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor d : descriptors) {
final Type type = d.getReadMethod().getGenericReturnType();
if (type instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) type;
System.out.println(d.getDisplayName());
for (Type atp : pt.getActualTypeArguments()) {
System.out.println(" " + atp);
}
}
}
Run Code Online (Sandbox Code Playgroud)
这里的关键是要读或写方法,并使用API Method.getGenericReturnType()或Method.getParameterTypes()分别.
请注意,处理java.lang.reflect.Type通常会非常繁琐/棘手,例如:
public Map<Nation, Map<A extends PostCode, B extends Location>> getGlobalPostCodes() { ... }
Run Code Online (Sandbox Code Playgroud)