Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the class of an n dimensional array of an runtime supplied class name

Given a fully qualified class name, and a number of dimensions, i would like to get the Class name for this class. I believe i can do this like such

public Class<?> getArrayClass(String className, int dimensions) throws ClassNotFoundException {
    Class<?> elementType = Class.forName(className);
    return Array.newInstance(elementType, new int[dimensions]).getClass();
}

However this requires me to create an unneeded instance of the class. Is there a way to do this without creating the instance?

It does not appear that Class.forName("[[[[Ljava/lang/String;") (or a algorithmically generated version) works correctly in all instances from various blog posts i've seen. (bugs.sun.com/bugdatabase/view_bug.do?bug_id=6434149)

like image 955
MeBigFatGuy Avatar asked Dec 04 '25 06:12

MeBigFatGuy


1 Answers

Using the [[[Ljava.lang.String; notation is the standard way of representing array class names.

The XMLEncoder and XMLDecoder use standard Java functionality to write and read arrays:

String[][][] foo = new String[3][4][5];
foo[0][0][0] = "a";
foo[2][3][4] = "z";
XMLEncoder encoder = new XMLEncoder(System.out);
encoder.writeObject(foo);
encoder.flush();
encoder.close();

yields the following result:

<?xml version="1.0" encoding="UTF-8"?> 
<java version="1.6.0_22" class="java.beans.XMLDecoder"> 
 <array class="[[Ljava.lang.String;" length="3"> 
  <void index="0"> 
   <array class="[Ljava.lang.String;" length="4"> 
    <void index="0"> 
     <array class="java.lang.String" length="5"> 
      <void index="0"> 
        <string>a</string> 
        ...

I currently don't see any problem in using Class.forName() with a self-built class name (e.g. prepending the [L, since it's also used by the Java standard classes in the same way.

Class arrayClass = Class.forName("[L" + "java.lang.String" + ";");

And as the JavaDoc for Class.forName describes, the class is loaded but not initialized, and you also don't need to create an instance for it.

If name denotes an array class, the component type of the array class is loaded but not initialized.

Your last remark about various blog posts where this would not work would be interesting to investigate.

like image 156
mhaller Avatar answered Dec 05 '25 19:12

mhaller



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!