获得组件类型的数组类 [英] Obtaining the array Class of a component type

查看:80
本文介绍了获得组件类型的数组类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有的实例,有没有获得实例的数组类型的一种方式?什么我基本要求的是一个方法是等效的 getArrayType 这是 getComponentType()方法的逆,使得:

  array.getClass()。getComponentType()。getArrayType()== array.getClass()


解决方案

所想到的一件事是:

  java.lang.reflect.Array.newInstance(组件类型,0).getClass();

但它带来不必要的实例。

顺便说一句,这似乎工作:

  clazz类=的Class.forName([L+ componentType.getName()+);

下面是测试。它打印真正

 整数[] = AR新的整数[1];
类组件类型= ar.getClass()getComponentType()。
clazz类=的Class.forName([L+ componentType.getName()+);的System.out.println(clazz所== ar.getClass());

的文档类#的getName() 严格定义数组类名的格式为:


  

如果这个类对象重新presents一类阵列,然后是名称的内部形式包括由一个或多个pceded元素类型$ P ​​$的名称的[字符重新presenting的深入阵列嵌套。


的Class.forName(..)办法不会直接元的工作,虽然 - 对他们来说,你不得不名称之间创建一个映射( INT )和数组速记 - ( I

If I have an instance of Class, is there a way of obtaining a Class instance for its array type? What I'm essentially asking for is the equivalent of a method getArrayType which is the inverse of the getComponentType() method, such that:

array.getClass().getComponentType().getArrayType() == array.getClass()

解决方案

One thing that comes to mind is:

java.lang.reflect.Array.newInstance(componentType, 0).getClass();

But it creates an unnecessary instance.

Btw, this appears to work:

Class clazz = Class.forName("[L" + componentType.getName() + ";");

Here is test. It prints true:

Integer[] ar = new Integer[1];
Class componentType = ar.getClass().getComponentType();
Class clazz = Class.forName("[L" + componentType.getName() + ";");

System.out.println(clazz == ar.getClass());

The documentation of Class#getName() defines strictly the format of array class names:

If this class object represents a class of arrays, then the internal form of the name consists of the name of the element type preceded by one or more '[' characters representing the depth of the array nesting.

The Class.forName(..) approach won't directly work for primitives though - for them you'd have to create a mapping between the name (int) and the array shorthand - (I)

这篇关于获得组件类型的数组类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆