java中的 varargs ( var-args)

访问量: 1037

refer to:  https://docs.oracle.com/javase/1.5.0/docs/guide/language/varargs.html  and  http://stackoverflow.com/questions/766559/when-do-you-use-varargs-in-java

(个人认为,不如直接传入一个 hash 来的简单, 例如所有的 rails view helper 方法,link_to 啥的)

其实就是 方法体声明 末尾的多个参数。  例如: format_content(String a, Object... objects)

In past 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);
The three periods after the final parameter's type indicate that the final argument may be passed as an array or as a sequence of arguments. Varargs can be used only in the final argument position. Given the new varargs declaration for MessageFormat.format, the above invocation may be replaced by the following shorter and sweeter invocation:

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

订阅/RSS Feed

Subscribe

分类/category