Java 中的 Reflect Array 類
java.lang.reflect 包的 Array 類提供了靜態方法來動態建立和訪問 Java 陣列。Array 允許在 get 或 set 操作期間進行擴充套件轉換,但如果發生縮小轉換,則會丟擲 IllegalArgumentException。
此類提供了 newInstance() 方法,getter 方法和 setter 方法。newInstance() 方法接受一個名為 Class 的類的物件,該物件代表所需的元件,並接受一個表示陣列長度的整數,建立並返回一個具有給定規格的陣列。
示例
import java.lang.reflect.Array;
import java.util.Arrays;
public class Reflection_ArrayExample {
public static void main(String args[]){
Integer [] intArray = (Integer[]) Array.newInstance(Integer.class, 5);
intArray[0] = 2001;
intArray[1] = 12447;
intArray[2] = 6358;
intArray[3] = 902;
intArray[4] = 6654;
System.out.println(Arrays.toString(intArray));
}
}輸出
[2001, 12447, 6358, 902, 6654]
此類的 getter 方法 getLong()、getInteger()、getLong() 等等接受一個物件形式的陣列和一個表示索引的整數,並返回指定索引中給定陣列的元素。
此類的 setter 方法 setLong()、setInteger()、setLong() 等等接受一個物件形式的陣列,一個表示索引的整數和一個相應資料型別的值,並在指定索引處設定給定值。
示例
import java.lang.reflect.Array;
import java.util.Arrays;
public class Reflection_ArrayExample {
public static void main(String args[]){
int [] intArray = (int[]) Array.newInstance(int.class, 5);
intArray[0] = 2001;
intArray[1] = 12447;
intArray[2] = 6358;
intArray[3] = 902;
intArray[4] = 6654;
Array.setInt(intArray, 1, 1111);
Array.setInt(intArray, 3, 3333);
Array.setInt(intArray, 4, 4444);
System.out.println(Arrays.toString(intArray));
System.out.println(Array.getInt(intArray, 1));
System.out.println(Array.getInt(intArray, 3));
System.out.println(Array.getInt(intArray, 4));
}
}輸出
[2001, 1111, 6358, 3333, 4444] 1111 3333 4444
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言
C++
C#
MongoDB
MySQL
Javascript
PHP