Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Casting Object to Array type

Tags:

java

I am using a web service that returns a plain object of the type "Object". Debug shows clearly that there is some sort of Array in this object so I was wondering how I can cast this "Object" to an Array (or similar)?

I tried the following:

Collection<String> arr = (Collection<String>) values; Vector<String> arr = (Vector<String>) values; ArrayList<String> arr = (ArrayList<String>) values; 

But nothing worked. I always get an InvocationTargetException.

What am I doing wrong?

Edit:

Sadly, I had to remove the link to the image that showed the output of Eclipse's debugger because it was no longer available. Please do not wonder why in the answers an image is mentioned that is not there anymore.

like image 705
Jens Avatar asked Oct 23 '09 06:10

Jens


People also ask

Can we convert object to array in java?

Java For TesterstoArray() returns an Object[], it can be converted to String array by passing the String[] as parameter.

Can you type cast arrays in java?

You can't cast an Object array to an Integer array. You have to loop through all elements of a and cast each one individually.

How do you add an object to an array in java?

Simply add the required element in the list using add() method. Convert the list to an array using toArray() method.


2 Answers

Your values object is obviously an Object[] containing a String[] containing the values.

String[] stringValues = (String[])values[0]; 
like image 114
gustafc Avatar answered Oct 04 '22 10:10

gustafc


What you've got (according to the debug image) is an object array containing a string array. So you need something like:

Object[] objects = (Object[]) values; String[] strings = (String[]) objects[0]; 

You haven't shown the type of values - if this is already Object[] then you could just use (String[])values[0].

Of course even with the cast to Object[] you could still do it in one statement, but it's ugly:

String[] strings = (String[]) ((Object[])values)[0]; 
like image 33
Jon Skeet Avatar answered Oct 04 '22 12:10

Jon Skeet