获得组件类型的数组类 [英] Obtaining the array Class of a component type
问题描述
如果我有类
的实例,有没有获得类
实例的数组类型的一种方式?什么我基本要求的是一个方法是等效的 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 aClass
instance for its array type? What I'm essentially asking for is the equivalent of a methodgetArrayType
which is the inverse of thegetComponentType()
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屋!