简体   繁体   中英

Invoke method with java reflection with list of parameters

I am currently trying to execute a method via Reflections, but the method parameters are only a list.

List<Object> params = List.of("param1", "param2", 3, "param4");
Method method = getMethod(); //returns the method
AppInstance instance = new AppInstance();
method.invoke(instance, params);

The method looks like:

public void myMethod(String param1, String param2, int param3, String param4){
    //some code
}

but Java treats them like

public void myMethod(List<Object> params){
    //some code
}

The problem is that the length of the parameters varies, the method can have any number of parameters.

Is there a way to solve this problem?

try this

Object[] params = new Object[]{"param1", "param2", 3, "param4"};
Method method = getMethod();
AppInstance instance = new AppInstance();
method.invoke(instance, params);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM