how to get a array class using classloader in java?

Viewed 1609

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?

3 Answers

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;".

Related