javaarraysbackwards-compatibilityvariadic-functions

Can I pass an array as arguments to a method with variable arguments in Java?


I'd like to be able to create a function like:

class A {
  private String extraVar;
  public String myFormat(String format, Object ... args){
    return String.format(format, extraVar, args);
  }
}

The problem here is that args is treated as Object[] in the method myFormat, and thus is a single argument to String.format, while I'd like every single Object in args to be passed as a new argument. Since String.format is also a method with variable arguments, this should be possible.

If this is not possible, is there a method like String.format(String format, Object[] args)? In that case I could prepend extraVar to args using a new array and pass it to that method.


Solution

  • The underlying type of a variadic method function(Object... args) is function(Object[] args). Sun added varargs in this manner to preserve backwards compatibility.

    So you should just be able to prepend extraVar to args and call String.format(format, args).