import java.lang.reflect.Array;
class Test {
// simple method
private static void printArray(Object obj) {
// if obj is not an array return
if (obj==null || !obj.getClass().isArray()) return;
int length = Array.getLength(obj); // get the length of the array
int i=0;
for (i=0;i<length;i++) {
Object o = Array.get(obj, i); // get the ith element
if (o==null || !o.getClass().isArray()) {
System.out.print(o+" ");
} else {
printArray(o);
}
}
System.out.println();
}
// user friendly that prints extra information
private static void printArray(Object obj, int level) {
// if obj is not an array return
if (obj==null || !obj.getClass().isArray()) return;
int length = Array.getLength(obj); // get the length of the array
// adding extra tabs depending on the dimension we are trying to print
String tab = "";
String del = "\t";
for (int i=0;i<level;i++) {
tab += del;
}
int i=0;
System.out.println(tab+"Array "+level);
if (i<length) {
Object o = Array.get(obj, i); // get the ith element
if (o==null || !o.getClass().isArray()) {
System.out.print(del+tab+o+" "); // print call with tabs
} else {
printArray(o, level+1);
}
}
for (i=1;i<length-1;i++) {
Object o = Array.get(obj, i);
if (o==null || !o.getClass().isArray()) {
System.out.print(o+" "); // print call without tabs
} else {
printArray(o, level+1);
}
}
if (i<length) {
Object o = Array.get(obj, i);
if (o==null || !o.getClass().isArray()) {
System.out.println(o); // println call for changing lines
} else {
printArray(o, level+1);
}
}
}
// calling previous private method to make sure that level is 0
public static void printArrayOfObjects(Object obj) {
printArray(obj, 0);
}
// main method
public static void main(String [] args) throws Exception {
Object obj1 = new int [2][3][4];
printArrayOfObjects(obj1);
// OR with values
int [][][] obj2 = new int [2][3][4];
obj2[0][0][0] = 5;
obj2[0][0][1] = 4;
obj2[0][0][2] = 2;
obj2[0][0][3] = 9;
obj2[0][1][0] = 1;
obj2[0][1][1] = 2;
obj2[0][1][2] = 3;
obj2[0][1][3] = 4;
obj2[0][2][0] = 4;
obj2[0][2][1] = 3;
obj2[0][2][2] = 2;
obj2[0][2][3] = 1;
obj2[1][0][0] = 50;
obj2[1][0][1] = 40;
obj2[1][0][2] = 20;
obj2[1][0][3] = 90;
obj2[1][1][0] = 10;
obj2[1][1][1] = 20;
obj2[1][1][2] = 30;
obj2[1][1][3] = 40;
obj2[1][2][0] = 40;
obj2[1][2][1] = 30;
obj2[1][2][2] = 20;
obj2[1][2][3] = 10;
printArrayOfObjects(obj2);
}
}