| Refresh | Home EGTry.com

find out dimesion of array object


package reflection;

import java.lang.reflect.Array;

public class ArrayType {

	public static void main(String[] args) {
		test(new int[2]);
		test(new float[1][2]);
		test(new int[2][3][4]);
	}
	
	public static void test(Object obj) {
		Class type=obj.getClass();
		int dim=getDim(type);
		String firstType=whatType(type);
		String name=firstType+"_"+dim+"Darray";
		System.out.println(name);
	}
	
	public static String whatType(Class type) {
		Class compType=type.getComponentType();
		if (compType==null) {
			return type.getSimpleName();
		} else {
			return whatType(compType);
		}
	}
	public static int getDim(Class compClass) {
		Class childClass=compClass.getComponentType();
		if (childClass==null) {
			return 0;
		} else {
			return getDim(childClass)+1;
		}
	}
}


output

int_1Darray
float_2Darray
int_3Darray