Reputation: 44094
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.
(new int[12]).getClass().getName()
returns [I
(new Date[2][]).getClass().getName()
returns [[Ljava.util.Date
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
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
Reputation: 116266
The simple name of an array is the simple name of the component type with "[]" appended.
Upvotes: 4