Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to invoke a getter method by its name?

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?

like image 266
user3663882 Avatar asked Feb 24 '15 13:02

user3663882


People also ask

How do I run getter?

We can invoke setters and getters of a POJO class by using its variable name by using Reflection API of java. Reflection API is used to examine the behavior of classes, interfaces, methods at runtime.

What is invoke () in java?

invoke() . The first argument is the object instance on which this particular method is to be invoked. (If the method is static , the first argument should be null .) Subsequent arguments are the method's parameters. If the underlying method throws an exception, it will be wrapped by an java.


2 Answers

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.

like image 115
Pshemo Avatar answered Oct 23 '22 12:10

Pshemo


Another easy way is to use the basic java reflection.

Method fieldGetter = A.getClass().getMethod("getField");
String f = fieldGetter.invoke(A).toString();

As simple as that. Cheers !!

like image 7
AnirbanDebnath Avatar answered Oct 23 '22 12:10

AnirbanDebnath