views:

62

answers:

2

Is there a way to specify the String name of a property in a particular bean and return the class that the getter corresponds to?

+2  A: 

You can use the java.beans.Introspector class to obtain information about a given bean. You can't query the BeanInfo for a specific property, but you can loop through them:

private Class<?> getPropertyType(Class<?> clazz, String property) {
    BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
    PropertyDescriptor[] propDescriptors = beanInfo.getPropertyDescriptors();
    for (PropertyDescriptor propDescriptor : propDescriptors) {
        // String name of a property
        if (property.equals(propDescriptor.getName())) {
           // Class the getter corresponds to.
           return propDescriptor.getPropertyType();
        }
    }
    ...
}
David Grant
Do you know if BeanUtil can do this?
DD
I guess so, but you probably ought to state that you're using Apache Commons before you ask the question!
David Grant
A: 

Found it... org.apache.commons.beanutils.PropertyUtils.getPropertyType(Object bean, String name)

DD