Monday, December 19, 2011

PropertyUtils.getProperty: Invoking Java Reflection


I needed a way to automatically call the getters and setters of a class. I knew, this is possible with Java Reflection but how, I did not know. Here is a simple example which shows how we will be able to invoke the generic property getter and setter operations on Java objects.

The example uses a class (Employye.java) and calls the employee.getName() method through reflection using PropertyUtils.getProperty(object, propertyName) and PropertyUtils.getProperty(object, propertyName, propertyValue) methods.

This example depends on the following three jars.
and

Please download trhe jars and add them to your project path.

  1. Employee Class:
Make the employee class as.

public class Employee {
private String name;
public String getName() {
            return name;
}
public void setName(String name) {
            this.name = name;
}
}
  1. Main Class
import org.apache.commons.beanutils.PropertyUtils;
public class PropertyUtilsExample {
            public static void main(String[] args) {
                        Employee e=new Employee();
                        e.setName("John");
                        try{
                        String s=(String)PropertyUtils.getProperty(e,"name");
                        System.out.println(s);
                        PropertyUtils.setProperty(e, "name","Mark");
                        s=(String)PropertyUtils.getProperty(e, "name");
                        System.out.println(s);
                        }catch(Exception ee){
                                   
                        }
            }

}

  1. Output:
Output of the program is

John
Mark  

Hope it helps someone, cheers.

No comments:

Post a Comment