可以使用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 + " ");
}
}