Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Obtaining an Array class with Java reflection

DZone's Guide to

Obtaining an Array class with Java reflection

· Java Zone
Free Resource

Learn how to troubleshoot and diagnose some of the most common performance issues in Java today. Brought to you in partnership with AppDynamics.

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!

 

Understand the needs and benefits around implementing the right monitoring solution for a growing containerized market. Brought to you in partnership with AppDynamics.

Topics:
java ,how-to ,reflection

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

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

{{ parent.tldr }}

{{ parent.urlSource.name }}