Java 如何按名称调用 getter 方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28697484/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to invoke a getter method by its name?
提问by user3663882
I have the following bean class:
我有以下bean类:
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?
如何获取特定对象的 getter 返回的值class A
?当然,我可以调用方法,Method.invoke(Object obj, Object... args)
但我不想"get"
手动编写前缀。有没有可能避免这种情况?
回答by Pshemo
How about using java.beans.PropertyDescriptor
怎么用 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()
PropertyDescriptor
允许我们做很多事情,例如它的 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.
所以我们可以得到java.reflect.Method
代表 getter for 的实例field
。我们现在需要做的只是在想要获得结果的 bean 上调用它。
回答by AnirbanDebnath
Another easy way is to use the basic java reflection.
另一种简单的方法是使用基本的 java 反射。
Method fieldGetter = A.getClass().getMethod("getField");
String f = fieldGetter.invoke(A).toString();
As simple as that. Cheers !!
就如此容易。干杯!!