Java: get all method parameters as Object array

6.5k views Asked by At

Is it possible to do this:

void foo(Bar b, FooBar fb){
    Object[] args=getArgs() //Contains the parameters b & fb
}

And if yes, how?

(I dont know the name and the number of parameters)

2

There are 2 answers

0
Nayuki On

No, Java does not support a simple, generic way to pack all the method arguments into an array. This is pretty standard for statically typed programming languages. It's generally dynamic languages like JavaScript and shell scripting languages that do allow retrieving all the arguments as an array.

0
dcsohl On

Given a method like you declare it, there is no (easy/standard) way to retrieve it as an Object[].

Now, you can always declare a method as

public void doSomething(Object... args) {
   Object o1 = args[0];  // etc
}

then you can call

doSomething(foo);
// or
doSomething(foo, bar, baz);

but you lose all type safety doing it this way; I don't really recommend it.