Roey Golzarpoor Roey Golzarpoor - 4 months ago 19
Java Question

Java reflection - how to call getter/setter method?

I'm trying to call set method of some property that I got in my object, my code goes like this:

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 goes 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:

public void setPagesAmount(int pagesAmount) {
this.pagesAmount = pagesAmount;
}


Any suggestions how to solve this issue?

Answer
currentObject.getClass().getMethod(methodName);

Since methods can be overloaded, just the name of 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).

Try something like

currentObject.getClass().getMethod(methodName, objectInputArr[i].getClass());
                                               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^