If you do not want to make the switch for all primitive types you could do like this:
if (ofArray.isPrimitive()) {
int length = Array.getLength(o);
for (int i = 0; i < length; i++) {
Object obj = Array.get(o, i);
System.out.println(obj);
}
}
else {
Object[] objects = (Object[]) o;
for (Object obj : objects) {
System.out.println(obj);
}
}
Edit: If you don't want to loop in two different places in your code use this method to convert the primitive arrays to an object array:
static Object[] convertToObjectArray(Object array) {
Class ofArray = array.getClass().getComponentType();
if (ofArray.isPrimitive()) {
List ar = new ArrayList();
int length = Array.getLength(array);
for (int i = 0; i < length; i++) {
ar.add(Array.get(array, i));
}
return ar.toArray();
}
else {
return (Object[]) array;
}
}
Answer from Vegard on Stack OverflowIf you do not want to make the switch for all primitive types you could do like this:
if (ofArray.isPrimitive()) {
int length = Array.getLength(o);
for (int i = 0; i < length; i++) {
Object obj = Array.get(o, i);
System.out.println(obj);
}
}
else {
Object[] objects = (Object[]) o;
for (Object obj : objects) {
System.out.println(obj);
}
}
Edit: If you don't want to loop in two different places in your code use this method to convert the primitive arrays to an object array:
static Object[] convertToObjectArray(Object array) {
Class ofArray = array.getClass().getComponentType();
if (ofArray.isPrimitive()) {
List ar = new ArrayList();
int length = Array.getLength(array);
for (int i = 0; i < length; i++) {
ar.add(Array.get(array, i));
}
return ar.toArray();
}
else {
return (Object[]) array;
}
}
This will work for arrays with elements that are sublcasses of Object:
if (clazz.isArray()) {
Object[] objects = (Object[]) o;
for (Object obj : objects)
System.out.println(obj);
}
If you need to cast the array to an specific array type you could (ab)use instanceof but for, say, just printing the contents as strings, an Object[] suffices.
UPDATE
If the array is of primitive types, you have no option but to test for each one and cast to the correct type, Object[] won't work for this case - but there aren't that many primitive types in Java, so it won't be a gigantic switch :) . This is what I mean:
if (clazz.isArray()) {
if (clazz.getComponentType().equals(double.class)) {
double[] numbers = (double[]) o;
for (double d : numbers)
System.out.println(d);
}
}
Another alternative to System.arraycopy:
String[] stringArray = Arrays.copyOf(objectArray, objectArray.length, String[].class);
In Java 8:
String[] strings = Arrays.stream(objects).toArray(String[]::new);
To convert an array of other types:
String[] strings = Arrays.stream(obj).map(Object::toString).
toArray(String[]::new);