我正在使用 method.invoke(instance, args...)
方式调用 Class 实例的一些方法,但是对于 instance
中的每个方法,作为invoke
Javadoc 正确地指出,必须手动指定每个参数。
考虑一下 Spring……在 HTTP 调用期间,它如何在幕后对 Controller 方法中的参数进行定价? (但我认为它确实以完全不同的方式......)
我想知道 Java 中是否有任何方法可以在反射(甚至不反射)中动态传递参数,而无需单独指定每个参数。
编辑
实例类声明是这样的:
public class Something {
public void doSth(String par1, String par2, Integer par3) {
//....
}
public void doSthElse(String par1, Boolean par2) {
//....
}
public void doSthElseMore(Integer par1) {
//....
}
}
我如何调用每个方法:
...
for (Method method : instance.getDeclaredMethods()) {
Object[] array = //BL: build array of values to pass to the invoke method.
//1. doSth may be new Object[] {"abc", "def", 123}
//2. doSthElse iteration may be new Object[] {"abc", false}
//3. doSthElseMore iteration may be new Object[] {123}
return method.invoke(instance, array);
}
...
如上所示,Something
类(实例
)中的每个方法都有不同数量的参数。
在每次迭代中,array
都有不同数量的值传递给 invoke
。
最佳答案
实际上,正如@Boris 所说,要完成我的工作,我要做的就是将每个参数转换为正确的类型。通过这种方式,Java 设法使用正确的参数类型调用 Something
类的正确方法。
我的项目是一个使用 Vavr
和 jodd
的 Vert.x
应用程序,但最后一个返回语句显示了我是如何设法解决的。
public Object invokeMethod(Object service, Method method, RoutingContext routingContext) throws Exception {
MultiMap queryParams = routingContext.queryParams();
Map<String, String> pathParams = routingContext.pathParams();
Buffer body = routingContext.getBody();
// 1. type, 2. name, 3. value
List<Tuple3<Class<?>, String, Object>> list = List.empty();
for (Parameter par : method.getParameters()) {
ParamQuery paramQuery = par.getAnnotation(ParamQuery.class);
if (paramQuery != null) {
list = list.push(new Tuple3<Class<?>, String, Object>(par.getType(), paramQuery.value(),
queryParams.get(paramQuery.value())));
}
}
// TypeConverterManager used to "covnert" each object (String) from the HTTP call to the correct data type
return method.invoke(service, list.reverse()
.map(mapper -> TypeConverterManager.lookup(mapper._1()).convert(mapper._3())).toJavaArray());
}
然而,这个项目可以在GitHub上找到
关于java - 通过动态参数反射调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50210343/