使用反射来检查 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 + " ");
   }
}

更新于: 2020 年 6 月 25 日

2K+ 次浏览

开启你的 职业生涯

完成课程即可获得认证

开始
广告
© . All rights reserved.