Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring - get class property value without using PropertyUtils(commons lib)

Tags:

java

spring

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) 
like image 678
user_27 Avatar asked Oct 19 '25 14:10

user_27


1 Answers

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.

like image 191
df778899 Avatar answered Oct 22 '25 04:10

df778899



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!