Reflection call getter methods of Pojo
Consider a scenario where a POJO consists of 100's of fields with getters and setters. And you want to display values of all the fields.
To achieve this, writing System.out.println for each getter would be a very tedioius job as shown below
Consider a Person class with Name, Address, etc. fields. So to print each value as shown below you need to write Sysout for each field
System.out.println("Name - " + object.getName());
System.out.println("Address - " + object.getAddress());
To simplify the process, we can use Reflection using the below classes
1) java.lang.reflect.Method
2) getName() method of above class
3) Checking if getName() startsWith "get"
Please refer the implementation below:
As shown in above example, Person object is created and values are set into the fields.
Next iteration through Method class where a condition is checked
1) method.getName().startsWith("get")
2) method.getGenericParameterTypes().length == 0 - It checks that the method should not accept any arguments. Generally if you follow Java Coding standards, then getter methods does not take any arguments.
Consider a scenario where a POJO consists of 100's of fields with getters and setters. And you want to display values of all the fields.
To achieve this, writing System.out.println for each getter would be a very tedioius job as shown below
Consider a Person class with Name, Address, etc. fields. So to print each value as shown below you need to write Sysout for each field
System.out.println("Name - " + object.getName());
System.out.println("Address - " + object.getAddress());
To simplify the process, we can use Reflection using the below classes
1) java.lang.reflect.Method
2) getName() method of above class
3) Checking if getName() startsWith "get"
Please refer the implementation below:
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import com.pojo.Person;
public class ReflectionCallGetters {
public static void main(String args[]) throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException {
Person person = new Person();
person.setAddress("Mumbai");
person.setAge(35);
person.setName("Bhatia");
Method[] methods = Person.class.getMethods();
for (Method method : methods) {
if (method.getName().startsWith("get") && method.getGenericParameterTypes().length == 0) {
Object returnObject = method.invoke(person);
System.out.println(method.getName() + " - " + returnObject);
}
}
}
}
As shown in above example, Person object is created and values are set into the fields.
Next iteration through Method class where a condition is checked
1) method.getName().startsWith("get")
2) method.getGenericParameterTypes().length == 0 - It checks that the method should not accept any arguments. Generally if you follow Java Coding standards, then getter methods does not take any arguments.
Thanks a lot, very helpful.
ReplyDeleteThanks for the Info.
ReplyDelete