开发者

Get the code name of a Class<Array>

开发者 https://www.devze.com 2023-02-28 21:15 出处:网络
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.

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

精彩评论

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

关注公众号