I want to get a property value from a bean in my spring project. In my project I don't have Commons BeanUtils. Also I don’t want to include that lib.
I need an alternative to the code statement below, in spring.
PropertyUtils.getProperty(entity, field)
The closest equivalent to Commons BeanUtils that comes built into the JDK is java.beans.Introspector
. This can analyse the getter and setter methods on a class, and return an array of PropertyDescriptor[]
.
Clearly this isn't as high-level - with this you need to hunt out the right property in that array. At a minimum (with no exception handling):
public static Object getProperty(Object bean, String propertyName) {
BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
PropertyDescriptor propertyDescriptor = Arrays
.stream(beanInfo.getPropertyDescriptors())
.filter(pd -> pd.getName().equals(propertyName)).findFirst()
.get();
return propertyDescriptor.getReadMethod().invoke(bean);
}
If you have Spring in the mix though, org.springframework.beans.BeanUtils
helps with finding that PropertyDescriptor
:
PropertyDescriptor propertyDescriptor = BeanUtils
.getPropertyDescriptor(bean.getClass(), propertyName);
This will also be more efficient over time - behind the scenes Spring is using CachedIntrospectionResults
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With