如果我有一个 Class
实例,是否有办法获取其数组类型的 Class
实例?我本质上要求的是方法 getArrayType
的等价物,它是 getComponentType()
方法的逆方法,这样:
array.getClass().getComponentType().getArrayType() == array.getClass()
最佳答案
我想到的一件事是:
java.lang.reflect.Array.newInstance(componentType, 0).getClass();
但它创建了一个不必要的实例。
顺便说一句,这似乎有效:
Class clazz = Class.forName("[L" + componentType.getName() + ";");
这是测试。它打印 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()
严格定义数组类名的格式:
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.
Class.forName(..)
方法不会直接适用于基元 - 对于它们,您必须在名称 (int
) 和数组简写 - (I
)
关于java - 获取组件类型的数组Class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58559104/