Get the code name of a Class<Array>
I'm doing some code g开发者_C百科eneration 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?
Try Class.getSimpleName()
.
The simple name of an array is the simple name of the component type with "[]" appended.
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()) + "[]";
}
}
精彩评论