Andrew
Andrew

Reputation: 89

How to call method with Object... as parameter

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.

Upvotes: 1

Views: 1429

Answers (3)

qrius
qrius

Reputation: 631

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()]);

Upvotes: 1

David Zimmerman
David Zimmerman

Reputation: 345

Pass an array.

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

Upvotes: 1

Allan Braga
Allan Braga

Reputation: 470

You can use var args:

method declaration:

void somemethod(Object ...){ }

And call this methodo with how many parameters you need.

Upvotes: 0

Related Questions