MeBigFatGuy
MeBigFatGuy

Reputation: 28568

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)

Upvotes: 3

Views: 812

Answers (2)

mhaller
mhaller

Reputation: 14232

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.

Upvotes: 2

Ravi
Ravi

Reputation: 301

The only way that i could think of is pass the class instead of string.

The point is that i am assuming here is, the calling class, may be for most of the cases be knowing the class.

public V[] getArrayClass(Class<V> c, int dimensions) throws ClassNotFoundException {
    return (V[])Array.newInstance(c, new int[dimensions]).getClass();
    /* The type cast is required. Since Array.newInstance 
   is not genrically parameterized. */
}

Upvotes: -1

Related Questions