Accessing JavaBean’s Getters and Setters

A JavaBeans is simply a Java class with a set of properties, each property which has a getter and/or a setter. For example if the Java class has a name property it could be defined like this.

public class Foo {
  private String mName;
  public String getName() { return mName; }
  public void setName(String pName) { mName = pName; }

Typically one accesses the property by directly calling its getter and/or setter. But sometimes you may not know the name of the property in advance but still might want to access the getter and/or setter. To do this one can use Java’s beans and reflection packages.

Here is an example of how one would read the value of a property of a JavaBean. Note that the property name should not be capitalized.

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;

public Object getProperty(MyBean myBean, String propertyName) {

  // get descriptor of property
  PropertyDescriptor descriptor = new PropertyDescriptor(propertyName, myBean.getClass());

  // invoke read method on property of myBean
  Method readMethod = descriptor.getReadMethod();
  return readMethod.invoke(memberSavingsProfile, (Object []) null);

Note that if your property only has a getter then you would create the PropertyDescriptor like this.

// get descriptor of property that only has a getter
String readMethodName = "get" + org.apache.commons.lang.StringUtils.capitalize(propertyName);
String writeMethodName = null;
PropertyDescriptor descriptor = new PropertyDescriptor(propertyName, myBean.getClass(), readMethodName, writeMethodName);