使用反射检查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 教师闺蜜祝福语简短