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?
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.
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.
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.
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 !!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With