java - 获取组件类型的数组Class

标签 java arrays

如果我有一个 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/

相关文章:

javascript - 检查上传文件是否受 Javascript 或 jQuery 密码保护

java - 如何在 Java 中旋转 BufferedImage?

java - 指定使用 T 的类

python - 如何在numpy中有效地从Nx3点云阵列获取表面点?

arrays - 使用 unicode 字符串对数组进行排序

php - 在不使用foreach In PHP的情况下,将方程式应用于关联数组的每个值

java - 通过命令行将空数组传递给 Dropwizard

java - 在Java中,远程对象也可以是客户端吗?

c - 有什么方法可以在 C 中使用具有常量索引的常量数组作为 switch case 标签?

ruby - 从 ruby​​ 中的标准输入获取整数数组的高效/直接方法