Calling a Method Using Reflection / Converting a List to Var Args

I have a list of parameters, and I have a method name. I want to call a method using reflection. When I checked the java document for Method.invoke, it looks like Method.invoke (object o, Object args ...). I know what to pass for the first parameter (for example, for a method that should be called if its instance method) and args are parameters for the method.

But now I have a list that contains the values ​​that should be passed to the method.

Let's say for example: I want to call the ClassName.methodName (String, int, int) method, and I have a List that contains {val1, 3, 4}.

Using reflection may be similar to Method.invoke (classNameInstance, ??????). But I'm not sure how to convert the argument list to varargs and pass.

One way could be. If I know that the size of the list is 3, then I can write Method.invoke (classNameInstance, list.get (0), list.get (1), list.get (2)).

But some of the methods that I want to dynamically call take from 0 to 12 arguments. So it does not look β€œgood” to create a switch case and record 12 cases. Each of them will check the number of parameters and build a separate call with parameters.

Is it possible to get around this, except using the switching case?

Any help would be greatly appreciated.

+3
source share
3 answers

... , Object []. Arraynotation. , .

+8

EDITED: , vararg:

        Class<?> c = int.class;
        Object array = Array.newInstance(c, list.size());
        for (int i = 0; i < list.size(); i++)
                Array.set(array, i, list.get(i));
        Test.class.getDeclaredMethod("test", array.getClass()).invoke(
                new Test(), new Object[] { array });

void m(X...p) , void m(X[] p). .

( ):

import java.util.*;
import java.lang.reflect.*;

class Test
{
        public static void main(String[] args) throws Exception
        {
                List<Integer> list = new ArrayList<Integer>();
                list.add(1); list.add(2); list.add(3);
                Test.class.getDeclaredMethod("test", Integer[].class).invoke(
                    new Test(), new Object[] { list.toArray(new Integer[0]) });
                int[] params = new int[list.size()];
                for (int i = 0; i < params.length; i++) params[i] = list.get(i);
                Test.class.getDeclaredMethod("test", int[].class).invoke(
                    new Test(), new Object[] { params });
        }

        public void test(int ... i) { System.out.println("int[]: " + i[0] + ", " + i[1] + ", " + i[2]); }
        public void test(Integer... i) { System.out.println("Integer[]" + Arrays.asList(i)); }
}
0

Varargs is just an array.

A method can be obtained this way if it accepts int...args:

Method method = MyClass.class.getMethod("someMethod", int[].class);
method.invoke(myInstance, argumentsList.toArray());
-1
source

All Articles