Java传播运算符 [英] Java spread operator
问题描述
我不确定我在这里使用的词汇,如果我错了,请纠正我。
I am not sure of the vocabulary I am using here, please correct me if I'm wrong.
在Javascript中,我有以下代码:
In Javascript, I had the following code:
let args = [1,2,3];
function doSomething (a, b, c) {
return a + b + c;
}
doSomething(...args);
正如您所见,当致电 doSomething
,我可以使用 ...
spread运算符,以便将我的参数转换为 1,2,3
。
As you can see, when calling doSomething
, I am able to use the ...
spread operator in order to "transform" my arguments into 1, 2, 3
.
现在,我正在尝试用Java做同样的事情。
Now, I'm trying to do the same thing with Java.
假设我有一个 Foo
类:
public class Foo {
public int doSomething (int a, int b, int c) {
return a + b + c;
}
}
现在我要拨打 doSomething
:
int[] args = {1, 2, 3};
我想使用像 doSomething(... args)之类的东西
而不是调用 doSomething(args [0],args [1],args [2])
。
I'd like to use something like doSomething (...args)
instead of calling doSomething(args[0], args[1], args[2])
.
我看到这在函数声明中是可行的,但我不想改变这样一个函数的实现。
I saw that this is possible in the declaration of functions, but I'd like not to change the implementation of such a function.
推荐答案
Java语言不提供运算符来执行此操作,但其类库可以提供您所需的功能。
Java language does not provide an operator to do this, but its class library has a facility to do what you need.
[来自OP的评论] Foo的开发者可以自己选择doSomething函数的参数数量。然后我就可以构造一个包参数并将其注入方法中。
[from OP's comment] The developer of Foo could choose himself the number of arguments that function doSomething takes. I would then be able to construct a "bag" of arguments and inject it in the method.
使用反射API ,这就是它的用途。它要求您在数组中打包参数。还需要做很多额外的工作,包括包装/解包单个方法参数和方法结果,但是你可以在运行时检查签名,构造一个数组,然后调用方法。
Use reflection API, this is what it is for. It requires you to package arguments in an array. There is a lot of extra work required, including wrapping/unwrapping individual method arguments, and method result, but you can check the signature at run-time, construct an array, and call the method.
class Test {
public static int doSomething(int a, int b, int c) {
return a + b + c;
}
// This variable holds method reference to doSomething
private static Method doSomethingMethod;
// We initialize this variable in a static initialization block
static {
try {
doSomethingMethod = Test.class.getMethod("doSomething", Integer.TYPE, Integer.TYPE, Integer.TYPE);
} catch (Exception e) {
}
}
public static void main (String[] ignore) throws java.lang.Exception {
// Note that args is Object[], not int[]
Object[] args = new Object[] {1, 2, 3};
// Result is also Object, not int
Object res = doSomethingMethod.invoke(null, args);
System.out.println(res);
}
}
以上代码打印6(演示)。
这篇关于Java传播运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!