Javabean Introspector - what is in my List?

275 Views Asked by At

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

There are 1 best solutions below

2
On

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.