使用反射检查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 2026新年祝福语简短语
14 新娘对伴娘祝福语简短
15 年后祝福语简短走心
16 简短有内涵的祝福语
17 新年恋人祝福语简短创意
18 生日祝福语贺卡老师简短