mardi 7 août 2018

Java Reflection - How can we get a particular method name as String instead of Hardcoding method Name

I have to call a particular method through Java reflection. Instead of passing hard coded method name, is it possible to pass the methodName as string.

For example

 public getAttribute(Object object, String className, String methodName){
     Class<?> clazz = Class.forName(className);
     Method method = clazz.getMethod(methodName);
     return method.invoke(object); }

Let us say I have a class

 @Getter
 @Setter 
 Class Student{
   String studentName;
   int rollNumber;
 }

Lets say, we have caller code

Student student = new Student();
student.setName("xyz");
System.out.println(getAttribute(student, Student.class.name(), "getStudentName"));

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.





Aucun commentaire:

Enregistrer un commentaire