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.
Student.class.getStudentName.getName()is not possible. I think this answer pretty much answers your question too: https://stackoverflow.com/questions/3023354/how-to-get-string-name-of-a-method-in-javaStudent.class.getStudentName.getName()be better than"getStudentName"? I understand that you could then use refactoring tools more easily if you needed to change the name in the future, but is there another reason you want to avoid hard coding the name?@Getterand@Setterannotations from? Lombok?