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

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

问题描述

如果我有一个 Class 的实例,有没有办法获得它的数组类型的 Class 实例?我本质上要求的是一个方法 getArrayType 的等价物,它是 getComponentType() 方法的逆方法,例如:

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()

推荐答案

想到的一件事是:

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() + ";");

这里是测试.它打印 true:

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());

Class#getName() 严格定义了数组类名的格式:

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.

Class.forName(..) 方法虽然不能直接用于原语 - 对于它们,您必须在名称 (int) 和数组简写 - (I)

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)

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

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