Over a million developers have joined DZone.

Obtaining an Array class with Java reflection

· Java Zone

Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code! Brought to you in partnership with ZeroTurnaround.

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!

 

The Java Zone is brought to you in partnership with ZeroTurnaround. Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code!

Topics:
java,how-to,reflection

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}