Search code examples
javaclassloader

how to get a array class using classloader in java?


I define a classloader name MyClassLoader as such.

cl = new MyClassLoader();

I could use cl to load my class A.

Class c = cl.loadClass();

but how to load a class which is A[].class?


Solution

  • Assuming your ClassLoader implementation, MyClassLoader is properly implemented, you'd simply pass the canonical name of the array class to the loadClass method. For example, if you were trying to load the Class for the class com.something.Foo, you'd use

    cl.loadClass("[Lcom.something.Foo");
    

    You have to know that the class name for Array types is the character [ appended X number of times, where X is the number of array dimensions, then the character L. You then append the qualified class name of the type of the array. And finally, you append the character ;.

    Therefore

    Class<?> clazz = Class.forName("[Lcom.something.Examples;");
    

    would get you the Class instance returned by A[].class if it was loaded by the same ClassLoader.

    Note that you won't be able to instantiate this type this way. You'll have to use Array.newInstance() passing in the Class object for A, for a one dimensional array, the Class object for A[] for a two dimensional array and so on.