Thursday, October 22, 2009

VarArgs in Java 5

I know this has been around for a while.  I’ve seen it, but didn’t really know what it was.  Turns out its a short hand for using arrays as an argument to a method.

If you are creating a method that takes variable arguments, it is common to supply the arguments in some sort of array.  Take for instance the MessageFormat type classes:

MessageFormat.format(String format, Object[] args);

In order to use this method, the caller would have to make the call something like:

MessageFormat.format(“Hello {0}, isn’t life {1}”, new Object[]{“world”,”swell”});

VarArgs allows you to shorthand this by declaring your method like:

MessageFormat.format(String format, Object… args);

Which can then be called like:

MessageFormat.format(“Hello {0}, isn’t life {1}”, “world”, “swell”);

The only stipulation is that your vararg argument is the last in the parameter list.  Java then autoboxes your arguments into an Object array for you.

Nice!

No comments: