1

I wonder how can I call a class method which are expecting Object...(Object[]) as parameter.

I can't know at compilation time now many parameters I need to pass to it, so I can't do like somemethod(1,2,3,4,5).

I'm doing big construction like:

if (param.lengts()==5) {
somemethod(1,2,3,4,5);
} elseif (param.lengts()==4) 
somemethod(1,2,3,4);
....

I was trying to pass List<> and ArrayList<> but without success. Is there a simple way how to convert my dynamic array to the method? I can't change method constructor.

Problem about to call the method, not with declare or read parameters inside the method.

7
  • How is somemethod declared? Commented Jun 1, 2018 at 14:35
  • what is a "method constructor"? --- The easiest way would probably to overload the method with all eight primitives: someMethod(boolean...), someMethod(byte...), ... ,someMethod(double....), someMethod(Object...). Commented Jun 1, 2018 at 14:36
  • He probably means that he can't change the method definition. Commented Jun 1, 2018 at 14:39
  • somemethod deslare as : public PrinterDocument(IPrintable... printables) { // } Commented Jun 1, 2018 at 14:39
  • You are dealing with a constructor, not a method. You need to pass instances of IPrintable instead of integers when calling that constructor. Commented Jun 1, 2018 at 14:40

3 Answers 3

1

You can use variable arguments for this:

private void somemethod(Integer.. array) {
}

And call it like this:

somemethod()    
somemethod(1)    
somemethod(1,2)

If you have an arraylist as an input, you can pass it as this:

someMethod(list.toArray(new Integer[list.size()]);
Sign up to request clarification or add additional context in comments.

4 Comments

This was not about this. Lets say i have input=ArrayList<integer> as input and i need to call like: somemethod(input[0],input[1],input[2]...input[input.length()-1])
Convert the list to an array using the toArray method of the list.
Andrew check my updated answer, as suggested by @Jonathan as well
I guest this is the one i was looking for. Thanks.
1

Pass an array.

Object[] params = ... build the array from the args 
somemethod(params);
...
void somemethod(Object... objs); 

Comments

0

You can use var args:

method declaration:

void somemethod(Object ...){ }

And call this methodo with how many parameters you need.

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.