Reputation: 1271
How do you pass an array of arguments, like python's f(*args)
?
Python: f(*args)
JavaScript: f.apply(this, args)
Ruby: f(*args)
Similar to Can I pass an array as arguments to a method with variable arguments in Java? and varargs and the '...' argument, but the function declaration doesn't use spread syntax.
void draw(int x, int y) {
...
}
In addition, is this possible when the arguments are not all the same type?
void draw(int x, String y) {
...
}
Upvotes: 0
Views: 457
Reputation: 25623
You can do this with reflection, but it's probably more performant to use cached method handles that you initialize once, then reuse as many times as you need.
class SpreadInvoker {
public static void draw1(int x, String y) {
System.out.printf("draw1(%s, %s)%n", x, y);
}
public void draw2(int x, int y) {
System.out.printf("draw2(%s, %s)%n", x, y);
}
static MethodHandle DRAW1;
static MethodHandle DRAW2;
public static void main(String[] args) throws Throwable {
DRAW1 = MethodHandles.lookup()
.findStatic(
SpreadInvoker.class,
"draw1",
MethodType.methodType(
void.class,
int.class,
String.class
)
)
.asSpreader(Object[].class, 2);
DRAW2 = MethodHandles.lookup()
.findVirtual(
SpreadInvoker.class,
"draw2",
MethodType.methodType(
void.class,
int.class,
int.class
)
).asSpreader(Object[].class, 2);
SpreadInvoker instance = new SpreadInvoker();
final Object[] args1 = { 13, "twenty-six" };
final Object[] args2 = { 13, 26 };
DRAW1.invoke(args1); // SpreadInvoker.draw1(13, "twenty-six")
DRAW2.invoke(instance, args2); // instance.draw2(13, 26)
}
}
Output:
draw1(13, twenty-six)
draw2(13, 26)
Note, however, that this is the sort of thing you'd do if you don't know what method you need to call at compile time. This sort of thing should almost never be necessary.
Upvotes: 2
Reputation: 23483
To pass unknown number of variables you would do:
public void getNumber(int...args){
...
}
to retrieve you would do:
args[0], args[1], args[2], ...
Upvotes: 0
Reputation: 2528
This style of calling methods is not usual for Java language, but possible with reflection API:
Method drawMethod = YourClass.class.getDeclaredMethod("draw", new Class[] { int.class, int.class });
drawMethod.invoke(null, (Object[]) args);
Upvotes: 1
Reputation: 8263
It is very similar in java, but all of them must be the same type:
Java: f(String... args);
It calls "Varargs" so you can google by this world for more information
Upvotes: 0