I am not sure of the vocabulary I am using here, please correct me if I'm wrong.
In Javascript, I had the following code:
let args = [1,2,3];
function doSomething (a, b, c) {
return a + b + c;
}
doSomething(...args);
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
.
Now, I'm trying to do the same thing with Java.
Let's say I have a Foo
class:
public class Foo {
public int doSomething (int a, int b, int c) {
return a + b + c;
}
}
And now I want to call the doSomething
:
int[] args = {1, 2, 3};
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 language does not provide an operator to do this, but its class library has a facility to do what you need.
[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.
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);
}
}
The above code prints 6 (demo).