Invoke Setters And Getters Of A POJO Class Using Variable Name At Runtime.
Posted By : Neha Yadav | 28-May-2018
We can invoke setters and getters of a POJO class by using its variable name by using Reflection API of java.
Reflection API is used to examine the behavior of classes, interfaces, methods at runtime.
When we make some generics methods, we will need some common behavior which will work with any kind of class. For example, a common insertion method, to insert any kind of class(entity) data in the database. This will reduce code redundancy and improve the performance of the program.
Reflection API of java make it possible for us.
We use Method class and its methods to achieve this goal.
Here is an example(Invoking getter method at runtime and get the desired output):-
HelloWorld.java
import java.lang.reflect.*;
public class HelloWorld{
String name;
public HelloWorld(String name){
this.name=name;
}
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
// this method does the work to invoke the method at runtime
protected String getValueFromObject(Object object, String fieldName) {
// get class
Class clazz = object.getClass() ;
if (clazz == null) {
return null;
}
Object valueObject =null;
// get object value using reflection
String getterName = "get" + fieldName;
try {
Method method = clazz.getDeclaredMethod(getterName);
valueObject = method.invoke(object,(Object[]) null);
} catch (Exception e) {
System.out.println(e);
}
return valueObject != null ? valueObject.toString() : "";
}
public static void main(String []args){
HelloWorld h = new HelloWorld("Hello World");
h.getName();
System.out.println(h.getValueFromObject(h,"Name"));
}
}
To Run it:-
$ javac HelloWorld.java
$ java HelloWorld
Output:-
Hello World
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Neha Yadav
Neha is a creative person. She is having good knowledge of core java, advance java, hibernate,spring boot. She likes to solve puzzles, sudoku. She is a fun loving person.