How to get the base class of a Array using java reflection.

If we use Java reflection to get the class of a object like String[][] strings; Java reflection will return [[Ljava.lang.String. But sometimes you may want to get the bases class e.g in this case java.lang.String. Following method can be used to do that. If you want to get the bass class of array object a you use this as Class c=getTypeOfArray(a.getClass());

public static Class getTypeOfArray(Class c){
        Class cls=null;
        while(true){
            if(c.isArray()){
                c=c.getComponentType();
            }else{
                cls=c;
                break;
            }
        }
        return cls;
    }

Comments

Popular posts from this blog

Create new Java Class files at runtime

Using iReport plugin for Jasper Reports in Netbeans

Fixing Error "Failed to load VMMR0.r0 (VERR_SUPLIB_WORLD_WRITABLE)" in Virtualbox