Java反射属性字符串名称 - >类数据类型

时间:2010-02-16 11:23:36

标签: java reflection

有没有办法在特定的bean中指定属性的String名称并返回getter对应的类?

2 个答案:

答案 0 :(得分:3)

您可以使用java.beans.Introspector类来获取有关给定bean的信息。您无法在BeanInfo查询特定属性,但可以循环访问它们:

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();
        }
    }
    ...
}

答案 1 :(得分:0)

发现它...... org.apache.commons.beanutils.PropertyUtils.getPropertyType(Object bean,String name)

相关问题