简体   繁体   English

方法签名中的Java“params”?

[英]Java “params” in method signature?

In C#, if you want a method to have an indeterminate number of parameters, you can make the final parameter in the method signature a params so that the method parameter looks like an array but allows everyone using the method to pass as many parameters of that type as the caller wants. 在C#中,如果您希望方法具有不确定数量的参数,则可以使方法签名中的最后一个参数成为params以便方法参数看起来像一个数组但允许使用该方法的每个人传递尽可能多的参数键入者想要的类型。

I'm fairly sure Java supports similar behaviour, but I cant find out how to do it. 我很确定Java支持类似的行为,但我无法找到如何做到这一点。

In Java it's called varargs , and the syntax looks like a regular parameter, but with an ellipsis ("...") after the type: 在Java中,它被称为varargs ,语法看起来像一个常规参数,但在类型后面带有省略号(“...”):

public void foo(Object... bar) {
    for (Object baz : bar) {
        System.out.println(baz.toString());
    }
}

The vararg parameter must always be the last parameter in the method signature, and is accessed as if you received an array of that type (eg Object[] in this case). vararg参数必须始终是方法签名中的最后一个参数,并且可以像访问该类型的数组一样进行访问(例如,在这种情况下为Object[] )。

This will do the trick in Java 这将在Java中发挥作用

public void foo(String parameter, Object... arguments);

You have to add three points ... and the varagr parameter must be the last in the method's signature. 您必须添加三个点...并且varagr参数必须是方法签名中的最后一个。

As it is written on previous answers, it is varargs and declared with ellipsis ( ... ) 正如它在以前的答案中写的那样,它是varargs并用ellipsis声明( ...

Moreover, you can either pass the value types and/or reference types or both mixed (google Autoboxing ). 此外,您可以传递值类型和/或引用类型,也可以同时传递混合(google Autoboxing )。 Additionally you can use the method parameter as an array as shown with the printArgsAlternate method down below. 此外,您可以将method参数用作数组,如下面的printArgsAlternate方法所示。

Demo Code 演示代码

public class VarargsDemo {

    public static void main(String[] args) {
        printArgs(3, true, "Hello!", new Boolean(true), new Double(25.3), 'a', new Character('X'));
        printArgsAlternate(3, true, "Hello!", new Boolean(true), new Double(25.3), 'a', new Character('X'));
    }

    private static void printArgs(Object... arguments) {
        System.out.print("Arguments: ");
        for(Object o : arguments)
            System.out.print(o + " ");

        System.out.println();
    }

    private static void printArgsAlternate(Object... arguments) {
        System.out.print("Arguments: ");

        for(int i = 0; i < arguments.length; i++)
            System.out.print(arguments[i] + " ");

        System.out.println();
    }

}

Output 产量

Arguments: 3 true Hello! true 25.3 a X 
Arguments: 3 true Hello! true 25.3 a X 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM