开发者

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()) + "[]";
   }
 }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜