Reputation: 23352
I am getting Object obj
from a method. obj = String[7]
. I am having difficulty in getting these 7 Strings and print them.
How can I get Strings out of it?
Upvotes: 0
Views: 155
Reputation: 533910
If you have no idea whether an array is an Object array or primitive array (which means you can't cast it) You can use the Array class.
Object arr = new int[]{1, 2, 3};
for (int i = 0, len = Array.getLength(arr); i < len; i++)
System.out.println(Array.get(arr, i));
If you know its a String[], make it that class.
Upvotes: 1
Reputation: 425448
If you're sure you have an array, you could use Arrays.toString()
:
System.out.println(Arrays.toString((Object[])obj));
Upvotes: 3
Reputation: 13374
Object obj = ...;
...
if (obj instanceof String[]) {
for (String element : ((String[]) obj)) { ... }
}
If you need to deal with various types of arrays, I would look into reflection APIs.
Upvotes: 2