How can I create a Java method that accepts a variable number of arguments?

前端 未结 7 733
野的像风
野的像风 2020-11-28 07:51

For example, Java\'s own String.format() supports a variable number of arguments.

String.format(\"Hello %s! ABC %d!\", \"World\", 123);
//=>          


        
7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-28 08:17

    This is known as varargs see the link here for more details

    In past java releases, a method that took an arbitrary number of values required you to create an array and put the values into the array prior to invoking the method. For example, here is how one used the MessageFormat class to format a message:

    Object[] arguments = {
        new Integer(7),
        new Date(),
        "a disturbance in the Force"
    };
        String result = MessageFormat.format(
            "At {1,time} on {1,date}, there was {2} on planet "
             + "{0,number,integer}.", arguments);
    

    It is still true that multiple arguments must be passed in an array, but the varargs feature automates and hides the process. Furthermore, it is upward compatible with preexisting APIs. So, for example, the MessageFormat.format method now has this declaration:

    public static String format(String pattern,
                                Object... arguments);
    

提交回复
热议问题