I have to call a particular method through Java reflection. Instead of passing hardcoded method name, is it possible to pass the method name as a string?
For example
public String getAttribute(Object object1, Object2, String className, String methodName){
Class<?> clazz = Class.forName(className);
Method method = clazz.getMethod(methodName);
return ObjectUtils.firstNonNull(null == object1 ? null: method.invoke(object1),null == object2 ? null: method.invoke(object2); }
Let us say I have a class
@Getter
@Setter
Class Student{
String studentName;
String address;
int rollNumber;
}
Lets say, we have caller code
Student student1 = new Student();// Student record from School 1
Student student2 = new Student(); // Student record from School 2
student2.setAddress("ABC");
System.out.println(getAttribute(student1, student2, Student.class.name(), "getAddress"));
Instead of passing hardcoded method name as parameter to getAttribute()
method, is there a way that I can use a method name that is not hardcoded?
For example, getAttribute(student, Student.class.name(), Student.class.getStudentName.getName())
so that we can easily make the changes to methods and variable of the student class when required without worrying on hardcoded method name constants.