Reflection: get the method with arbitrary number of arguments and use it as such

I want to use a method from a 3rd party package I use. This is the signature:

java.lang.String buildMenuPath(java.lang.Object... objects);

The method can be used as follows (to name a few):

  1. buildMenuPath(1,1,1) //3 ints
  2. buildMenuPath("str",1,1) // 1 string 2 ints
  3. buildMenuPath("str",1) // 1 string 1 int

Through reflection, I try to get this method and follow usage #2 and #3.

Attempt #1, getting the exact signature I will use (String.class, Integer.class)

ArrayList pathArr = new ArrayList();
pathArr.add("Window");
pathArr.add(i);
Method method  = myObj.getClass().getMethod("buildMenuPath",String.class, Integer.class);
method.invoke(myObj,pathArr.toArray())
  • Throws: java.lang.NoSuchMethodException

Attempt #2, getting the arbitrary arguments method:

ArrayList pathArr = new ArrayList();
pathArr.add("Window");
pathArr.add(i);
Method method  = myObj.getClass().getMethod("buildMenuPath",Object[].class);
method.invoke(myObj,pathArr.toArray())
  • Looks like it gets the method but throws: java.lang.IllegalArgumentException

But if I call manually, with myObj.buildMenuPath("Window",6); it works.

How can I solve this problem through reflection?

1 answer

  • answered 2018-04-17 06:08 oviuan

    You need to know the exact signature of the function (look through documentation), it may take a variable list of arguments of Object type for example, or it may be overloaded, but the argument types may not be String and int.

    Finally, when calling Invoke(), cast the array of arguments to (Object)

    In your case, should be:

    ArrayList pathArr = new ArrayList();
    pathArr.add("Window");
    pathArr.add(i);
    Method method  = myObj.getClass().getMethod("buildMenuPath",Object[].class);
    method.invoke(myObj,(Object)pathArr.toArray())