Java Reflection Beans Property API

Troydm picture Troydm · May 2, 2011 · Viewed 52.7k times · Source

Is there any standard way to access Java Bean Property like

class A {
   private String name;

   public void setName(String name){
       this.name = name;
   }

   public String getName(){
       return this.name;
   }

}

So can I access this java bean property name using Reflection API so that when I change the value of property the methods of getName and setName are called automatically when I set and get values of that property

Answer

Sean Patrick Floyd picture Sean Patrick Floyd · May 2, 2011

What you need is the BeanInfo / Introspector mechanism (see Bozho's answer). However, it's hell to use this directly, so you can use one of the Libraries that offer property-based access. The best-known is probably Apache Commons / BeanUtils (another one is Spring's BeanWrapper abstraction)

Example code:

A someBean = new A();

// access properties as Map
Map<String, Object> properties = BeanUtils.describe(someBean);
properties.set("name","Fred");
BeanUtils.populate(someBean, properties);

// access individual properties
String oldname = BeanUtils.getProperty(someBean,"name");
BeanUtils.setProperty(someBean,"name","Barny");