Bart van Heukelom
Bart van Heukelom

Reputation: 44094

Get the code name of a Class<Array>

I'm doing some code generation using reflection and need to get the string describing certain array types in code. The default API doesn't really make this easy.

The result is parseable, but is there an easier, nicer way to get int[] and java.util.Date[][] from those two, respectively?

Upvotes: 2

Views: 189

Answers (2)

Joachim Sauer
Joachim Sauer

Reputation: 308041

There's no built-in method that returns the "nice name" (a.k.a the name as written in Java source code),

getSimpleName() returns the "nice" name: it returns only the class name without the package and appends [] as necessary.

If you need the fully-qualified names with [], then you'd need to construct that manually:

 public static String getName(final Class<?> clazz) {
   if (!clazz.isArray()) {
     return clazz.getName();
   } else {
     return getName(clazz.getComponentType()) + "[]";
   }
 }

Upvotes: 3

P&#233;ter T&#246;r&#246;k
P&#233;ter T&#246;r&#246;k

Reputation: 116266

Try Class.getSimpleName().

The simple name of an array is the simple name of the component type with "[]" appended.

Upvotes: 4

Related Questions