0

In JavaScript, we can call a function using each item in an array as seperate arguments. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator

// Using the spread operator
function myFunction(x, y, z) { }
var args = [0, 1, 2];
myFunction(...args);

// Using the .apply method
function myFunction(x, y, z) { }
var args = [0, 1, 2];
myFunction.apply(null, args);

Is there any equivalent in Java?

balupton
  • 47,113
  • 32
  • 131
  • 182
  • 1
    I would assume that Java would just use an overloaded method instead. – Compass Jun 20 '16 at 16:23
  • No, but if `myFunction` was declared to take a [varargs](http://docs.oracle.com/javase/1.5.0/docs/guide/language/varargs.html) parameter, then an array can be given instead, e.g. `void myFunction(int ... values)` can be called using `myFunction(0, 1, 2)` or `int[] args = {0, 1, 2}; myFunction(args)`. – Andreas Jun 20 '16 at 16:25
  • Ahh yes, reflection. Nice find @hotzst. It's more cumbersome to write and you have to know the parameter types, but that'll do it for an `Object[]`, without special requirements for the method signature. – Andreas Jun 20 '16 at 16:28

0 Answers0