如何在Java中像Python的f(*args)一样传递参数?

13 投票
4 回答
7812 浏览
提问于 2025-04-16 03:19

在Python中,我可以这样做:

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

这在Java中可以做到吗?

为了更清楚一点,f的参数列表是可变长度的。

4 个回答

2

在Java中,有两种使用可变参数(varargs)的方法。

public static void main(String... args)

或者

public static void main(String[] args)

在我的例子中,我使用的是字符串,但你也可以用整数(int)来做。

调用这些方法时(这两种方法都适用),

main("hello", "world");

或者

main(new String[]{"hello", "world"});
4

你可以用可变参数(varargs)来声明一个方法,然后用一个数组来调用这个方法,正如其他回答所提到的那样。

如果你想调用的方法没有可变参数,你可以使用一种叫做反射的技术来实现,虽然这样做有点麻烦:

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);
9

当然,你可以使用可变参数方法来做到这一点。如果你对像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

不能对一个非可变参数的方法这样做。不过,非可变参数的方法参数数量是固定的,所以你应该能做到

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

而且,编译器无法根据数组的大小或类型来解决重载方法的情况

撰写回答