Java 反射 - 如何调用 getter/setter 方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28385850/
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
Java reflection - how to call getter/setter method?
提问by roeygol
I'm trying to call set method of some property that I got in my object, my code goes like this:
我正在尝试调用我在对象中获得的某些属性的 set 方法,我的代码如下:
String[] fieldsStringName = (((CacheObject)currentObject).getFieldsToString(false)).split(", ");
String methodName = "";
for (int i = 0; i < objectInputArr.length; i++) {
methodName = "set" + fieldsStringName[i];
Method methodSetProperty = currentObject.getClass().getMethod(methodName); <<----error occurs here
methodSetProperty.invoke(currentObject, objectInputArr[i]);
}
The error that i'm getting is:
我得到的错误是:
Exception in thread "main" java.lang.NoSuchMethodException: model.Book.setPagesAmount()
at java.lang.Class.getMethod(Unknown Source)
at CahceSystem.createNewObject(CahceSystem.java:84)
at CahceSystem.main(CahceSystem.java:50)
The requested setter method is well written in the class and also in it's super class (inherited propeties only), all my setter's methods are like:
请求的 setter 方法在类和它的超类中写得很好(仅限继承属性),我所有的 setter 方法都像:
public void setPagesAmount(int pagesAmount) {
this.pagesAmount = pagesAmount;
}
Any suggestions how to solve this issue?
任何建议如何解决这个问题?
回答by aioobe
currentObject.getClass().getMethod(methodName);
currentObject.getClass().getMethod(methodName);
Since methods can be overloaded, just the nameof the method is not enough to look up the method. You need to provide the types of the arguments as well (and a setter is typically not a no-arg method).
由于方法是可以重载的,所以仅仅通过方法的名称来查找方法是不够的。您还需要提供参数的类型(并且 setter 通常不是无参数方法)。
Try something like
尝试类似
currentObject.getClass().getMethod(methodName, objectInputArr[i].getClass());
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
回答by Rathakrishnan Duraimoni
*Field[] fields = currentObject.getClass().getDeclaredFields();
for (Field field :fields) {
Method method = student.getClass().getMethod("set"+field.getName()
.replaceFirst(field.getName().substring(0, 1), field.getName()
.substring(0, 1).toUpperCase()),field.getType());
}*
try the above snippet. its working fine
试试上面的代码片段。它的工作正常