3

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)

8
  • 5
    Object[] args = new Object[] {b, fb}; Why? Commented Jun 9, 2015 at 19:43
  • 2
    Or more direct: Object[] args = { b, fb };. Commented Jun 9, 2015 at 19:45
  • 2
    Yes you do know the name and number of arguments: Two arguments b and fb. Commented Jun 9, 2015 at 19:47
  • 1
    Of course you know the names of the parameters. They're declared right above. Commented Jun 9, 2015 at 19:47
  • 2
    Above ways are straightforward. If, on the other hand, you are looking for an arguments object a-la JavaScript, then no, we don't have access to such an object in Java. Commented Jun 9, 2015 at 19:48

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.