Reputation: 23587
I am looking for alternate to BeanUtils.getProperty()
.only reason i want to have alternate is to avoid end user having one more dependency.
I am working on a custom constraints and this is piece of code i have
final Object firstObj = BeanUtils.getProperty(value, this.firstFieldName);
final Object secondObj = BeanUtils.getProperty(value, this.secondFieldName);
Since i need to get these two properties out of object.
Is there any alternate for this without any third party system or i need to copy this piece of code from BeanUtilsBean
?
Upvotes: 12
Views: 20565
Reputation: 3708
If you use SpringFramework, "BeanWrapperImpl" its the answer you are looking for:
BeanWrapperImpl wrapper = new BeanWrapperImpl(sourceObject);
Object attributeValue = wrapper.getPropertyValue("attribute");
Upvotes: 22
Reputation: 51473
BeanUtils is very powerful because it supports nested properties. E.G "bean.prop1.prop2", handle Map
s as beans and DynaBeans.
For example:
HashMap<String, Object> hashMap = new HashMap<String, Object>();
JTextArea value = new JTextArea();
value.setText("jArea text");
hashMap.put("jarea", value);
String property = BeanUtils.getProperty(hashMap, "jarea.text");
System.out.println(property);
Thus in your case I would just write a private method that uses the 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;
}
Upvotes: 5