Java反射技術除了可以在運行時動態(tài)地決定要創(chuàng)建什么類型的對象,訪問哪些成員變量,方法,還可以動態(tài)地創(chuàng)建各種不同類型,不同維度的數(shù)組。
動態(tài)創(chuàng)建數(shù)組的步驟如下:
1.創(chuàng)建Class對象,通過forName(String)方法指定數(shù)組元素的類型
2.調用Array.newInstance(Class, length_of_array)動態(tài)創(chuàng)建數(shù)組
訪問動態(tài)數(shù)組元素的方法和通常有所不同,它的格式如下所示,注意該方法返回的是一個Object對象
Array.get(arrayObject, index)
為動態(tài)數(shù)組元素賦值的方法也和通常的不同,它的格式如下所示, 注意最后的一個參數(shù)必須是Object類型
Array.set(arrayObject, index, object)
動態(tài)數(shù)組Array不單可以創(chuàng)建一維數(shù)組,還可以創(chuàng)建多維數(shù)組。步驟如下:
1.定義一個整形數(shù)組:例如int[] dims= new int{5, 10, 15};指定一個三維數(shù)組
2.調用Array.newInstance(Class, dims);創(chuàng)建指定維數(shù)的數(shù)組
訪問多維動態(tài)數(shù)組的方法和訪問一維數(shù)組的方式沒有什么大的不同,只不過要分多次來獲取,每次取出的都是一個Object,直至最后一次,賦值也一樣。
動態(tài)數(shù)組Array可以轉化為普通的數(shù)組,例如:
Array arry = Array.newInstance(Integer.TYPE,5);
int arrayCast[] = (int[])array;
A. 一維數(shù)組:
public static void main(String args[]) throws Exception {
Class<?> classType = Class.forName("java.lang.String");
// 創(chuàng)建一個長度為10的字符串數(shù)組
Object array = Array.newInstance(classType, 10);
// 把索引位置為5的元素設為"hello"
Array.set(array, 5, "hello");
// 獲得索引位置為5的元素的值
String s = (String) Array.get(array, 5);
System.out.println(s);
}
Class<?> classType = Class.forName("java.lang.String");
// 創(chuàng)建一個長度為10的字符串數(shù)組
Object array = Array.newInstance(classType, 10);
// 把索引位置為5的元素設為"hello"
Array.set(array, 5, "hello");
// 獲得索引位置為5的元素的值
String s = (String) Array.get(array, 5);
System.out.println(s);
}
B. 多維數(shù)組:
public static void main(String args[]) {
int[] dims = new int[] { 5, 10, 15 };
// 創(chuàng)建一個具有指定的組件類型和維度的新數(shù)組。
Object array = Array.newInstance(Integer.TYPE, dims);
// 取出三維數(shù)組的第3行,為一個數(shù)組
Object arrayObj = Array.get(array, 3);
Class<?> cls = arrayObj.getClass().getComponentType();
System.out.println(cls);
// 取出第3行的第5列,為一個數(shù)組
arrayObj = Array.get(arrayObj, 5);
// 訪問第3行第5列的第10個元素,為其賦值37
Array.setInt(arrayObj, 10, 37);
// 動態(tài)數(shù)組和普通數(shù)組的轉換:強行轉換成對等的數(shù)組
int arrayCast[][][] = (int[][][]) array;
System.out.println(arrayCast[3][5][10]);
}
int[] dims = new int[] { 5, 10, 15 };
// 創(chuàng)建一個具有指定的組件類型和維度的新數(shù)組。
Object array = Array.newInstance(Integer.TYPE, dims);
// 取出三維數(shù)組的第3行,為一個數(shù)組
Object arrayObj = Array.get(array, 3);
Class<?> cls = arrayObj.getClass().getComponentType();
System.out.println(cls);
// 取出第3行的第5列,為一個數(shù)組
arrayObj = Array.get(arrayObj, 5);
// 訪問第3行第5列的第10個元素,為其賦值37
Array.setInt(arrayObj, 10, 37);
// 動態(tài)數(shù)組和普通數(shù)組的轉換:強行轉換成對等的數(shù)組
int arrayCast[][][] = (int[][][]) array;
System.out.println(arrayCast[3][5][10]);
}
-------------------------------------------------------------
生活就像打牌,不是要抓一手好牌,而是要盡力打好一手爛牌。