mercredi 8 mai 2019

Is there a reason Java reflection getMethod sometimes does not work?

I have some code using reflection which I would like to use to call a setter method.

Method getObjectMethod = entityClass.getMethod(GET_METHOD_NAME);
if (getObjectMethod != null){
     Object p = getObjectMethod.invoke(obj);
     Class<?> pClass = p.getClass();

     Method setMethod = null;
     Method[] methodList = pClass.getDeclaredMethods();
     for (Method met: methodList){
         if (met.getName().equals(SET_METHOD_NAME)) {
             setVersionMethod = met;
             break;
          }
     }

     if (setMethod != null){
          setMethod.invoke(p, "UPDATED BY REFLECTION5");
      }

This works fine.

However when I try to replace the loop with

setMethod = pClass.getDeclaredMethod(SET_METHOD_NAME);

or setMethod = pClass.getMethod(SET_METHOD_NAME);

I get a NoSuchMethodException.

Any idea why ?





Aucun commentaire:

Enregistrer un commentaire