使用反射检查Java中的数组类型和长度
可以使用java.lang.Class.getComponentType()方法检查数组类型。此方法返回表示数组的组件类型的类。可以使用java.lang.reflect.Array.getLength()以int形式获得数组长度。
演示此的程序如下所示-
示例
import java.lang.reflect.Array;
public class Demo {
public static void main (String args[]) {
int[] arr = {6, 1, 9, 3, 7};
Class c = arr.getClass();
if (c.isArray()) {
Class arrayType = c.getComponentType();
System.out.println("The array is of type: " + arrayType);
System.out.println("The length of the array is: " + Array.getLength(arr));
System.out.print("The array elements are: ");
for(int i: arr) {
System.out.print(i + " ");
}
}
}
}输出结果
The array is of type: int The length of the array is: 5 The array elements are: 6 1 9 3 7
现在让我们了解上面的程序。
首先定义数组arr,然后使用该getClass()方法获取arr的运行时类。演示这的代码片段如下-
int[] arr = {6, 1, 9, 3, 7};
Class c = arr.getClass();然后使用getComponentType()方法获得数组类型。数组的长度是使用Array.getLength()方法获得的。最后,显示数组。演示这的代码片段如下-
if (c.isArray()) {
Class arrayType = c.getComponentType();
System.out.println("The array is of type: " + arrayType);
System.out.println("The length of the array is: " + Array.getLength(arr));
System.out.print("The array elements are: ");
for(int i: arr) {
System.out.print(i + " ");
}
}热门推荐
6 保研的祝福语简短
10 年轻20岁祝福语简短
11 朋友结婚祝福语信息简短
12 女孩婚礼贺卡祝福语简短
13 30段点歌简短祝福语
14 虎年春节祝福语图文简短
15 写给后妈祝福语大全简短
16 简短回复生日祝福语
17 校长送毕业祝福语简短
18 毕业立体贺卡祝福语简短