Java reflection - how to call getter / setter method?

I am trying to call the set method of some property that I got in my object, my code is as follows:

    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 I get 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, as well as the superclass in it (only inherited propositions), all my setter methods are like:

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

Any suggestions for resolving this issue?

+4
source share
2 answers
currentObject.getClass().getMethod(methodName);

Since methods can be overloaded, just the method name is not enough to find the method. You also need to specify argument types (and the installer is usually not a method without arguments).

Try something like

currentObject.getClass().getMethod(methodName, objectInputArr[i].getClass());
                                               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+5
source
*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());
}*

.

0

All Articles