1

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 Answers 2

3

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();
        }
    }
    ...
}
Sign up to request clarification or add additional context in comments.

2 Comments

Do you know if BeanUtil can do this?
I guess so, but you probably ought to state that you're using Apache Commons before you ask the question!
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.