Obtaining an Array class with Java reflection
This morning I needed to find and invoke a method reflectively that had an array parameter. It took me a few minutes to figure out how to get the class representing say a char[].
As a reminder, some other ways to get Class instances are:
- Class.forName("my.SillyClass") - for obtaining the Class for my.SillyClass by name
- SillyClass.class - for obtaining the class by type (preferred to the above for type safety)
- Integer.TYPE - for obtaining the Class for any primitive type via their wrapper class
An array is an object and has a class, but I wasn't aware of any way to do the equivalent of the above for an array of some type. One way is to use Class.forName() with the array class signature:
- Class.forName("[C") - for a char[]
- Class.forName("[Ljava.lang.String;") - for a String[]
But then my Java guru Tim Eck pointed out that you can just do:
- char[].class - for a char[]
Hope that helps someone out there!
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)





Comments
Bob Lee replied on Wed, 2008/03/12 - 2:35pm
I've run into ClassLoaders which didn't support using forName() like that.
Here's another approach:
Class<?> elementType = ...;
Class<?> arrayType = Array.newInstance(elementType, 0).getClass();
Alex Miller replied on Wed, 2008/03/12 - 2:49pm
Eugene Kuleshov replied on Wed, 2008/03/12 - 5:11pm
Onur Ersen replied on Thu, 2008/03/13 - 5:00am
Hello Alex,
I remembered that I read some information about reflections and arrays as you've mentioned.I found the article that I read among sun developer documents.
http://java.sun.com/developer/technicalArticles/ALT/Reflection/
Hope it also helps to those really wondering what you are trying to tell about java reflection,creating instances dynamically & arrays.
Regards,
ONur.
Luke replied on Wed, 2008/04/02 - 8:17pm
in response to:
Bob Lee
ClassLoaders aren't required to support the syntax at all. I'm guessing you were calling the ClassLoader directly?
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6500212
The three-argument form of Class.forName is the way to go if you need to use a particular ClassLoader, as I understand. (Though your reflection call works just as well, I imagine. What's a zero-length array instantiation among friends? :-) )