使用反射检查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 + " ");
}
}热门推荐
10 朋友新年祝福语大全 简短
11 新年祝福语简短大方兔年
12 搬新家礼物祝福语简短
13 同学见面花束祝福语简短
14 五一假期祝福语幽默简短
15 离职欢送敬酒祝福语简短
16 对学弟的祝福语简短
17 考老师辞职祝福语简短
18 祝福语驱散霉运的话简短