Over a million developers have joined DZone.
Platinum Partner

Obtaining an Array class with Java reflection

· Java Zone

The Java Zone is brought to you in partnership with AppDynamics. Discover how AppDynamics steps in to upgrade your performance game and prevent your enterprise from these top 10 Java performance problems.

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 AppDynamics. AppDynamics helps you gain the fundamentals behind application performance, and implement best practices so you can proactively analyze and act on performance problems as they arise, and more specifically with your Java applications. Start a Free Trial.

Topics:
java,how-to,reflection

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

{{ parent.tldr }}

{{ parent.urlSource.name }}