使用反射來檢查 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 + " ");
}
}
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP