Is there any way to invoke getter/setter method from my code , if I get the property name of a pojo in java? suppose I have a simple pojo class student

student{
   private String name;
   private int age;

   public String getName(){
      return name;
   }
   public int getAge(){
      return age;
   }
}

now in I got the prop name , say age and I have the student object , can I invoke the getAge() method.

I know reflection is the solution , but I did not found any efficient to do this. Can any one help me with some efficient and simple sample code to do this...

Thanks a lot...

3 Answers

2
hkn On Best Solutions

You can use Introspector:

import java.beans.Introspector;
import java.beans.PropertyDescriptor;


...
String name = "age";
Class beanClass = Student.class;
BeanInfo beanInfo = Introspector.getBeanInfo(beanClass);
PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor descriptor : descriptors) {
    if (!name.equals(descriptor.getName())) {
        continue;
    }
    descriptor.getWriteMethod();
    descriptor.getReadMethod()
}
0
Yugansh On

Try using BeanUtils ,

Employee employee= new Employee ();

BeanUtils.setProperty(employee,"employeeName","Xyz ABC");
Object value = PropertyUtils.getProperty(employee, "employeeName");

assuming you know all the fields of Employee object has:

private String employeeName;
0
tevemadar On

Well, you can do the call if you really want to:

public class Student {
    private String name;
    private int age;
    public String getName(){
       System.out.println("getName called");
       return name;
    }
    public int getAge(){
       System.out.println("getAge called");
       return age;
    }
}

public class Test {
    public static void main(String[] args) throws Exception {
        Student s=new Student();
        System.out.println(s.getClass().getMethod("getName").invoke(s));
        System.out.println(s.getClass().getMethod("getAge").invoke(s));
    }
}

Produces

getName called
null
getAge called
0

And if you have "name" or "age" in string something, the task which remains is to do something like

"get"+something.substring(0,1).toUpperCase()+something.substring(1)