mik01aj mik01aj - 3 months ago 14
Java Question

How to pass args to method in java, like f(*args) in python?

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.

Answer

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.