How to invoke a getter method by its name?

user3663882 picture user3663882 · Feb 24, 2015 · Viewed 34.6k times · Source

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?

Answer

Pshemo picture Pshemo · Feb 24, 2015

How about using java.beans.PropertyDescriptor

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.