In python, I can do:
args = [1,2,3,4]
f(*args) # this calls f(1,2,3,4)
Is this possible in java?
to clarify - f has an argument list of variable length.
Sure, you should be able to do precisely that using vararg-methods. If you're worried about ambiguities when it comes to arguments such as Object...
this piece of code should clarify:
public class Test {
public static void varargMethod(Object... args) {
System.out.println("Arguments:");
for (Object s : args) System.out.println(s);
}
public static void main(String[] args) throws Exception {
varargMethod("Hello", "World", "!");
String[] someArgs = { "Lorem", "ipsum", "dolor", "sit" };
// Eclipse warns:
// The argument of type String[] should explicitly be cast to Object[]
// for the invocation of the varargs method varargMethod(Object...)
// from type Test. It could alternatively be cast to Object for a
// varargs invocation
varargMethod(someArgs);
// Calls the vararg method with multiple arguments
// (the objects in the array).
varargMethod((Object[]) someArgs);
// Calls the vararg method with a single argument (the object array)
varargMethod((Object) someArgs);
}
}
Output:
Arguments:
Hello
World
!
Arguments:
Lorem
ipsum
dolor
sit
Arguments:
Lorem
ipsum
dolor
sit
Arguments:
[Ljava.lang.String;@1d9f953d
You can not do it for a non-vararg method. However, a non-vararg method has a fixed number of arguments, so you should be able to do
nonVarargMethod(args[0], args[1], args[2]);
Further more, there is no way to let the compiler resolve the situation for overloaded methods based on the size or type of the array.
A method can be declared with a varargs parameter, and invoked with an array, as suggested by other answers.
If the method you want to invoke doesn't have a varargs parameter, you can do something like this with introspection, though it's a bit clunky:
class MyClass {
public void myMethod(int arg1, String arg2, Object arg3) {
// ...code goes here...
}
}
Class<MyClass> clazz = MyClass.class;
Method method = clazz.getMethod("myMethod", Integer.TYPE, String.class, Object.class);
MyClass instance = new MyClass();
Object[] args = { Integer.valueOf(42), "Hello World", new AnyObjectYouLike() };
method.invoke(instance, args);
There is two way to use varargs in java
public static void main(String... args)
Or
public static void main(String[] args)
In my example it's with string, but you can do it with int too.
To call them (this works on both),
main("hello", "world");
or
main(new String[]{"hello", "world"});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With