简体   繁体   English

java.reflection:如何使用动态数量的args进行method.invoke(clazz,varargs)?

[英]java.reflection: How can I do method.invoke(clazz, varargs) with dynamic number of args?

I want to do method calls using reflection via method.invoke(clazz, varargs) with varying number of arguments and realize this way the call of different methods with one call only and not via explicit, hard coded number of arguments. 我想通过method.invoke(clazz,varargs)通过反射使用可变数量的参数来进行方法调用,并以这种方式实现仅通过一次调用即可调用不同方法的方法,而不是通过显式的硬编码参数来实现。 In the moment I do the following: 目前,我执行以下操作:

... 
determine method arguments via reflection
...
if (numberOfArguments == 0) {
    method.invoke(clazzInstance, null);
} else if (numberOfArguments == 1) {
    method.invoke(clazzInstance, arg0);
} else if (numberOfArguments == 2) {
    method.invoke(clazzInstance, arg0, arg1);
} ... etc

is there a way to do this more elegantly without the need for explicitly checking for the number of arguments? 有没有一种方法可以更优雅地完成此操作,而无需显式检查参数数量?

Collect arg0 , arg1 , argsN into an Object[] array, truncate the size to numberOfArguments and pass it: arg0arg1argsN收集到Object[]数组中,将大小截断为numberOfArguments并将其传递:

Object[] args = {arg0, arg1, ..., argsN};
method.invoke(clazzInstance, Arrays.copyOfRange(args, 0, numberOfArguments));

varargs are passed as an array, so you must create this array like in: varargs作为数组传递,因此您必须像下面这样创建此数组:

var args = Arrays.asList(arg1, ...).toArray()

or 要么

var args = List.of(arg1, ...).toArray()

or even create a method, eventually the one you are already writing, receiving the varargs 甚至创建一个方法,最终是您已经在编写的方法,接收了varargs

void method(Object... args) {
    ...

All the above options having the method invoked like 上面所有具有调用方法的选项

method.invoke(instance, args);

it all depends on the whole context 这一切都取决于整个环境

Varargs are (almost) treated as arrays, that is, type... args is the same as type[] args inside the method, the compiler just convert the arguments to an array when calling such a method. Varargs(几乎)被视为数组,即type... args与方法内部的type[] args相同,编译器仅在调用此类方法时将参数转换为数组。

if the method that you are invoking accept variable number of args of the same type, like 如果您要调用的方法接受可变数量的相同类型的args,例如

method(type...arg)

you can just use an array as a parameter 您可以只使用数组作为参数

method.invoke(clazzInstance, arg[])

If the arguments are of different type I don't advise you to do a method like method(Object[]...obj) because you don't put any restriction on the types that the method have to work with, and this can lead to some error devolping the code 如果参数的类型不同,我不建议您使用method(Object [] ... obj)之类的方法,因为您对方法必须使用的类型没有任何限制,这可以导致代码分解时出错

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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