简体   繁体   中英

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 ?

我想你想像这样使用java.lang.reflect.Array.newInstance() -

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM