Javabean Introspector - what is in my List?

北城以北 提交于 2019-12-12 01:47:00

问题


I use this code to find out all Java List in a given class:

BeanInfo beanInfo = Introspector.getBeanInfo(classx);
PropertyDescriptor[] propertyDescriptors = beanInfo .getPropertyDescriptors();

for (PropertyDescriptor pd : propertyDescriptors) {
    Class<?> ptype = pd.getPropertyType();

    if ((ptype+"").contains("java.util.List")) {
        System.out.println("list class property: " + pd.getName() + ", type=" + ptype); 
    }
}

This is the output:

class property: value, type=interface java.util.List

The question is how to find out what type is in the List? For this example this list is defined in classx as:

@JsonProperty("value")
private List<Value> value = new ArrayList<Value>();

How can I know the list is a list of Value objects? Thanks.


回答1:


You can not get that via Property introspection, due to Type Erasure. Anything with type Class has no generic type parameter information (directly at least; super-type relationships do). To get to generic type declarations you need to be able to access java.lang.reflect.Type (of which Class is one implementation; but ones with generic parameters are GenericType).

There are libraries that allow you to fully resolve generic types, for example java-classmate. It will give you access to fully resolved type information for Fields and Methods, but from that point you will need to figure out logical Bean properties. It is probably possible to combine the two, if you want, so that you could use Bean Introspection for finding Methods, then match that with resolved information java-classmate can offer.



来源:https://stackoverflow.com/questions/30947603/javabean-introspector-what-is-in-my-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!