Search code examples
javamethodsparameterscall

Can a method with arbitrary number of arguments, be called with an array?


I would like to call a method which signature is

public void foo(Object object, Object ... objects) { }

and I call it like

Object[] objects = ...;
foo(objects);

as the compiler does'nt complain it seems valid, but what happens with the first parameter in the signature? Is it objects[0]

Can anyone explain the Object ... objects parameter, what happens internal?

I can't change the method, it's from Method class.


Solution

  • Varargs are effectively a different syntax to describe arrays so in principle yes. But since you defined the first parameter explicitly you'd have to pass that separately.

    The problem with vargs is that you also could not pass any parameter, i.e. an array of length 0. That's probably why you want to declare the first parameter explicitly, which is ok IMO. You just can't call it the way you want.

    With your method signature the following should work:

    foo("first");
    foo("first", "second", "third");
    foo("first", new String[]{"second", "third"} );
    

    The problem with your definition, i.e. using Object is that arrays are objects as well, so the call you described above is basically like foo("first").

    Edit:

    Since the method you mention is Method.invoke(Object object, Object ... objects) it's obvious why there are 2 parameters. The first is the target of execution, i.e. the instance the method should be invoked on, while the second is the array of parameters.

    One could rewrite that signature to Method.invoke(Object object, Object[] objects) but calling it without first creating an array (even if of length 0) is more awkward or you'd need another method that just accepts one parameter in order to call no-arg methods.