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?
I think you want to use java.lang.reflect.Array.newInstance() like this -
A[] arr = java.lang.reflect.Array.newInstance(A.class, 10); /* for example */
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.
ClassNotFoundException with that class. What is decode?ClassLoader, and these kind of names won't work there. Doing this with the static Class.forName method is not the same, as you have no good control over what ClassLoader will it use.In Java 12, you can call someClass.arrayType() to get the "array of someClass" class. If you need a two dimensional array, that will be someClass.arrayType().arrayType(). Of course, you can load someClass itself like Class<?> someClass = someClassLoader.loadClass("com.example.A").
I couldn't find a solution in the standard API of earlier Java versions, so I have written this utility method:
/**
* Returns the array type that corresponds to the element type and the given number of array dimensions.
* If the dimension is 0, it just returns the element type as is.
*/
public static Class<?> getArrayClass(Class<?> elementType, int dimensions) {
return dimensions == 0 ? elementType : Array.newInstance(elementType, new int[dimensions]).getClass();
}
And then you can do this:
Class<?> arrayClass = getArrayClass(someClass, 1);
Kind of an ugly workaround, but... unlike with Class.forName, you control what ClassLoader is used, and you don't have to write another utility to generate funny names like "[[I" or "[Lcom.example.A;".
A[].class? Do you want to do it at run time where you don't know whatAis?