Java Method.invoke() throwing IllegalArgumentException: argument type mismatch

2.8k views Asked by At

I am trying to invoke a static method with a Object[] parameter type. When I debug, the correct method is identified and the parameter type I put in seems to me to be of the correct type.

public String convertToJSFunction(Method method, Object[] params) {

    String function = method.getName();

    for (Method m : JavaToJS.class.getDeclaredMethods()) {
        if (m.getName().equals(function))
            try {
                return (String) m.invoke(null,params);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
                return null;
            } catch (InvocationTargetException e) {
                e.printStackTrace();
                return null;
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
                return null;
            }
    }

    return null;
}

JavaToJS has only static methods. After debugging, the m I am trying to invoke is this method:

public static String setRegionNumber(Object[] params)

This throws an IllegalArgumentException: argument type mismatch. How is this possible?

1

There are 1 answers

0
André R. On BEST ANSWER

i guess you are calling

Method setRegionNumber=...; // "setRegionNumber" Method
Object[] params=...; // your Object-Array Parameter
convertToJSFunction(setRegionNumber, params);

but what you need to do is

Method setRegionNumber=...; // "setRegionNumber" Method
Object[] params=...; // your Object-Array Parameter
convertToJSFunction(setRegionNumber, new Object[] { params });

this is because Method.invoke expects the parameter list of the called method as an object Array. So if you pass your object array directly then it interprets that as the parameter list. so if you have an Object[] Parameter you need to wrap it in an Object-Array just like any other parameter.