How to invoke a getter method by its name?

getter, java, methods

Solution

How about using `java.beans.PropertyDescriptor` (assuming your property has correct setter and getter - so in your case you need to correct your `private String setField(String field)` setter since (a) its return type should be `void` not `String`, (b) it should be `public` not `private`).

Object f = new PropertyDescriptor("field", A.class).getReadMethod().invoke(a);

or little longer version (which does exactly same as previous one)

PropertyDescriptor pd = new PropertyDescriptor("field", A.class);
Method getter = pd.getReadMethod();
Object f = getter.invoke(a);

`PropertyDescriptor` allows us to do many things, for instance its `getReadMethod()`

Gets the method that should be used to read the property value.

So we can get instance of `java.reflect.Method` representing getter for `field`. All we need to do now is simply invoke it on bean from which we want to get result.

Problem

I have the following bean class: ``` public class A{ private String field; public String getField() { return field; } private String setField(String field) { this.field = field; } } ``` And the following class: ``` public class B{ public static void main(String[] args){ A a = new A(); //do stuff String f = //get a's field value } } ``` How can I get the value returned by the getter of a particular object of `class A`? Of course, I can invoke method with `Method.invoke(Object obj, Object... args)` but I wouldn't like to write `"get"` prefix manually. Is it possible to avoid that?

Original source

Related problems