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!
Alex Miller lives in St. Louis. He writes code for a living and currently work for Terracotta Tech on the Terracotta open-source Java clustering product. Prior to Terracotta he worked at BEA Systems and was Chief Architect at MetaMatrix. His main language for the last decade has been Java, although Alex have been paid to program in several languages over the years (C++, Python, Pascal, etc). Alex is a DZone MVB and is not an employee of DZone and has posted 43 posts at DZone. You can read more from them at their website.
- Login or register to post comments
- 5903 reads
- Printer-friendly version
(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: bl92550
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? :-) )