ngesh
ngesh

Reputation: 13501

casting object to String[] object..?

Assume the following scenario. i call a method like this

String[] arr = {"1","2","3"};
method(arr);

and the method signature is

public void method(Object o)
{
// how will i get back the String[] arr object now.. 
}

Upvotes: 0

Views: 213

Answers (4)

Peter Lawrey
Peter Lawrey

Reputation: 533492

If you are writing

public void method(Object o) {
   String[] arr = (String[]) o;
}

this means the only valid parameter type is String[] and you are better off making this clear with

public void method(String[] arr) {

}

Upvotes: 1

Harry Joy
Harry Joy

Reputation: 59660

public void method(Object o) {
   String[] arr = (String[]) o;
}

Here o is your passed String[] object. Just cast it to String[]. And if you are planning to pass an array every time then change your method signature to:

public void method(Object[] o)

Upvotes: 1

Nico Huysamen
Nico Huysamen

Reputation: 10417

Just cast it back.

String[] o2 = (String[]) o;

Upvotes: 1

KARASZI István
KARASZI István

Reputation: 31467

The casting would look like this:

final String[] array = (String[]) o;

Upvotes: 3

Related Questions