jeudi 24 mai 2018

Unable to invoke the method with variable arguments using reflection in java

When the method m is ( where m is the method to be invoked using reflection )

public static Optional<JsonNode> concat(ObjectNode entity, String separator, String fieldName1,
          String fieldName2) 

Then i am able to get the computed value ( where computed value is the value obtained using reflection )

While, when the method m is

public static Optional<JsonNode> concat(ObjectNode entity, String ...separatorAndField)

then i am able not able to get the computed value

I am invoking the method as follows:-

   computedValue = (Optional<JsonNode>) m.invoke(null, methodArgs);

Note:- methodArgs is declared as an object array.

Edit:- Added the full code

Object[] inputArgArray = null;
      String functionName = evalExp.substring(0, evalExp.indexOf('('));
      String functionArgsString = evalExp.substring(evalExp.indexOf('(') + 1, evalExp.indexOf(')'));
      if (StringUtils.isNotBlank(functionArgsString)) {
        inputArgArray = functionArgsString.split(",");
      } else {
        inputArgArray = new Object[0];
      }
      Class<?>[] paramTypes = new Class[inputArgArray.length + 1];
      Object[] methodArgs = new Object[inputArgArray.length + 1];
      paramTypes[0] = ObjectNode.class;// pass input entity as argument
      methodArgs[0] = entity;
      for (int i = 1; i < inputArgArray.length + 1; i++) {
        paramTypes[i] = String.class;
        methodArgs[i] = inputArgArray[i - 1];
      }
      Method m = EvalAttributeOperations.class.getDeclaredMethod(functionName, paramTypes);
      computedValue = (Optional<JsonNode>) m.invoke(null, methodArgs);
    } catch (NoSuchMethodException | SecurityException | IllegalAccessException
        | IllegalArgumentException | InvocationTargetException e) {
      log.error(e.getMessage(), e);
      throw new BackendException("Error occured while evaluating function", e);
    }
    return computedValue;
  }





Aucun commentaire:

Enregistrer un commentaire