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

mik01aj:

在python中,我可以执行以下操作:

args = [1,2,3,4]
f(*args) # this calls f(1,2,3,4)

这在Java中可能吗?

要澄清-f具有可变长度的参数列表。

aioobe:

当然,您应该能够使用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);
    }
}

输出:

Arguments:
    Hello
    World
    !
Arguments:
    Lorem
    ipsum
    dolor
    sit
Arguments:
    Lorem
    ipsum
    dolor
    sit
Arguments:
    [Ljava.lang.String;@1d9f953d

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

nonVarargMethod(args[0], args[1], args[2]);

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章