要使用反射機制動態載入類別並生成陣列的話,可以使用java.lang.reflect.Array來協助,下
面這個例子簡單的示範了如何生成String陣列:
package onlyfun.caterpillar;
import java.lang.reflect.Array; public class NewArrayDemo { public static void main(String[] args) { Class c = String.class; Object objArr = Array.newInstance(c, 5); for(int i = 0; i < 5; i++) { Array.set(objArr, i, i+""); } for(int i = 0; i < 5; i++) { System.out.println(Array.get(objArr, i)); } } }
執行結果:
二維以上陣列的話,可以透過一個int陣列來宣告其維度,例如下面這個程式示範如何設定與取得二維陣列的值:
package onlyfun.caterpillar; import java.lang.reflect.Array; public class NewArrayDemo { public static void main(String[] args) { Class c = String.class; int[] dim = new int[]{3, 4}; Object objArr = Array.newInstance(c, dim); for(int i = 0; i < 3; i++) { Object row = Array.get(objArr, i); for(int j = 0; j < 4; j++) { Array.set(row, j, "" + (i+1)*(j+1)); } } for(int i = 0; i < 3; i++) { Object row = Array.get(objArr, i); for(int j = 0; j < 4; j++) { System.out.print(Array.get(row, j) + " "); } System.out.println(); } } }
執行結果:
|
|