如何将args传递给java中的方法,比如python中的f(*args)?

mik*_*1aj 9 python java arguments variadic-functions

在python中,我可以这样做:

args = [1,2,3,4]
f(*args) # this calls f(1,2,3,4)
Run Code Online (Sandbox Code Playgroud)

这在Java中可行吗?

澄清 - f有一个变长的参数列表.

aio*_*obe 7

当然,您应该能够使用vararg-methods精确地做到这一点。如果您在涉及诸如Object...这段代码之类的参数时担心模棱两可,则应澄清:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

Arguments:
    Hello
    World
    !
Arguments:
    Lorem
    ipsum
    dolor
    sit
Arguments:
    Lorem
    ipsum
    dolor
    sit
Arguments:
    [Ljava.lang.String;@1d9f953d
Run Code Online (Sandbox Code Playgroud)

对于非可变参数方法,您不能这样做。但是,非可变参数方法具有固定数量的参数,因此您应该能够做到

nonVarargMethod(args[0], args[1], args[2]);
Run Code Online (Sandbox Code Playgroud)

此外,没有办法让编译器根据数组的大小或类型来解决重载方法的情况