Sunday, September 26, 2010

Spring's BeanWrapper

I was searching for an utily class to get dinamically the properties of a bean. The first one I analyzed is BeanUtils.getSimpleProperty from Apache BeanUtils. The usage is quite simple and intuitive:
String myProp = BeanUtils.getSimpleProperty(Object bean, String name);
After searching for a while I discovered another way to do it, which allow me to do the same without using another library. Since I'm already using Spring in my project, the easiest way is to use a class from the framework, the Spring's BeanWrapper:
BeanWrapper newWrapper = PropertyAccessorFactory.forBeanPropertyAccess(bean);
String myProp = (String) newWrapper.getPropertyValue(name);  
As the APIs say, this interface supports nested properties enabling the setting of properties on subproperties to an unlimited depth, that is exactly what I was searching for.