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 ( 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.

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) {
   = name;
  1. Main Class
import org.apache.commons.beanutils.PropertyUtils;
public class PropertyUtilsExample {
            public static void main(String[] args) {
                        Employee e=new Employee();
                        String s=(String)PropertyUtils.getProperty(e,"name");
                        PropertyUtils.setProperty(e, "name","Mark");
                        s=(String)PropertyUtils.getProperty(e, "name");
                        }catch(Exception ee){


  1. Output:
Output of the program is


Hope it helps someone, cheers.

No comments:

Post a Comment