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.
commons-beanutils.jar
(http://commons.apache.org/beanutils/download_beanutils.cgi),
commons-collections.jar
(http://commons.apache.org/collections/download_collections.cgi)
and
commons-logging.jar
(http://commons.apache.org/logging/download_logging.cgi)
Please
download trhe jars and add them to your project path.
- 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;
}
}
- 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){
}
}
}
- Output:
Output of the program is
John
Mark
Hope it helps someone, cheers.
No comments:
Post a Comment