BeanUtils非常强大,因为它支持嵌套属性. E.G“bean.prop1.prop2”,将Maps作为bean和DynaBeans处理.
例如:
HashMap hashMap = new HashMap();
JTextArea value = new JTextArea();
value.setText("jArea text");
hashMap.put("jarea", value);
String property = BeanUtils.getProperty(hashMap, "jarea.text");
System.out.println(property);
因此,在您的情况下,我只会编写一个使用java.beans.Introspector的私有方法.
private Object getPropertyValue(Object bean, String property)
throws IntrospectionException, IllegalArgumentException,
IllegalAccessException, InvocationTargetException {
Class> beanClass = bean.getClass();
PropertyDescriptor propertyDescriptor = getPropertyDescriptor(
beanClass, property);
if (propertyDescriptor == null) {
throw new IllegalArgumentException("No such property " + property
+ " for " + beanClass + " exists");
}
Method readMethod = propertyDescriptor.getReadMethod();
if (readMethod == null) {
throw new IllegalStateException("No getter available for property "
+ property + " on " + beanClass);
}
return readMethod.invoke(bean);
}
private PropertyDescriptor getPropertyDescriptor(Class> beanClass,
String propertyname) throws IntrospectionException {
BeanInfo beanInfo = Introspector.getBeanInfo(beanClass);
PropertyDescriptor[] propertyDescriptors = beanInfo
.getPropertyDescriptors();
PropertyDescriptor propertyDescriptor = null;
for (int i = 0; i < propertyDescriptors.length; i++) {
PropertyDescriptor currentPropertyDescriptor = propertyDescriptors[i];
if (currentPropertyDescriptor.getName().equals(propertyname)) {
propertyDescriptor = currentPropertyDescriptor;
}
}
return propertyDescriptor;
}