Java 數組反射

Java 數組反射

我們可以使用Class類中的isArray()方法來檢查類是否是數組。

我們可以創建一個數組,使用反射通過讀取和修改其元素的值 java.lang.reflect.Array 類。

Array類的 getLength()方法獲取數組的長度。

Array類中的所有方法都是靜態的。

要創建數組,請使用Array類中的重載靜態方法newInstance()。

Object newInstance(Class> componentType, int arrayLength)
Object newInstance(Class> componentType, int... dimensions)

第一個方法根據指定的組件類型和數組長度創建一個數組。

第二個版本創建指定組件類型和尺寸的數組。

newInstance()方法的返回類型是Object,我們需要將它轉換為實際的數組類型。

下面的代碼創建一個長度為5的 int 數組。

int[] ids = (int[])Array.newInstance(int.class, 5);

要創建一個維度為5乘3的int數組。

int[][] matrix = (int[][])Array.newInstance(int.class, 5, 3);

例子

以下代碼顯示瞭如何動態創建數組並操作其元素。

import java.lang.reflect.Array;
public class Main {
public static void main(String[] args) {
try {
Object my = Array.newInstance(int.class, 2);
int n1 = Array.getInt(my, 0);
int n2 = Array.getInt(my, 1);
System.out.println("n1 = " + n1 + ", n2=" + n2);
Array.set(my, 0, 11);
Array.set(my, 1, 12);
n1 = Array.getInt(my, 0);
n2 = Array.getInt(my, 1);
System.out.println("n1 = " + n1 + ", n2=" + n2);
} catch (NegativeArraySizeException | IllegalArgumentException
| ArrayIndexOutOfBoundsException e) {
System.out.println(e.getMessage());
}
}
}

上面的代碼生成以下結果。

Java 數組反射

獲取數組的維度

Java支持array數組。

類中的 getComponentType()方法返回數組的元素類型的Class對象。

以下代碼說明了如何獲取數組的維度。

public class Main {
public static void main(String[] args) {
int[][][] intArray = new int[1][2][3];
System.out.println("int[][][] dimension is " + getArrayDimension(intArray));
}
public static int getArrayDimension(Object array) {
int dimension = 0;
Class c = array.getClass();
if (!c.isArray()) {
throw new IllegalArgumentException("Object is not an array");
}
while (c.isArray()) {
dimension++;
c = c.getComponentType();
}
return dimension;
}
}

上面的代碼生成以下結果。

Java 數組反射

展開數組

Java數組是一個固定長度的數據結構。

要放大數組,我們可以創建一個更大尺寸的數組,並將舊數組元素複製到新數組元素。

以下代碼顯示如何使用反射展開數組。

import java.lang.reflect.Array;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] ids = new int[2];
System.out.println(ids.length);
System.out.println(Arrays.toString(ids));
ids = (int[]) expandBy(ids, 2);
ids[2] = 3;
System.out.println(ids.length);
System.out.println(Arrays.toString(ids));
}
public static Object expandBy(Object oldArray, int increment) {
Object newArray = null;
int oldLength = Array.getLength(oldArray);
int newLength = oldLength + increment;
Class> c = oldArray.getClass();
newArray = Array.newInstance(c.getComponentType(), newLength);
System.arraycopy(oldArray, 0, newArray, 0, oldLength);
return newArray;
}
}

上面的代碼生成以下結果。

Java 數組反射


分享到:


相關文章: