Java原始碼分析——java.lang.reflect反射包解析(二) Array類,陣列的建立
阿新 • • 發佈:2018-11-12
在Java中,引用型別中有那麼幾個特殊的類,Object類是所有類的起源、Class類定義所有類的抽象與行為、ClassLoader類實現了類從.class檔案中載入進jvm,而Array陣列類,則實現了陣列手動的建立。
Array陣列類,是個不可被繼承的類:
public final
class Array {
private Array() {}
}
而且構造方法是私有的,不能直接建立該類,其中有兩種創造陣列的方法,第一種格式如下:
public static Object newInstance(Class<?> componentType, int length)
throws NegativeArraySizeException {
return newArray(componentType, length);
}
private static native Object newArray(Class<?> componentType, int length)
throws NegativeArraySizeException;
它呼叫的newArray是native方法,它接受兩個引數,一個Class類物件表明陣列存貯的內容,另外一個表明陣列的長度。如下面示例程式碼:
public class Test {
public static void main(String args[]) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
int []test= (int[]) Array.newInstance(int.class,10);
for (int i=0;i<test.length;i++){
test[i]=1;
}
for (int i=0;i<test.length;i++){
System.out.print(test[i]+" ");
}
}
//輸出為:1 1 1 1 1 1 1 1 1 1
另外一種格式是用來創造多維陣列的,其原始碼如下:
public static Object newInstance(Class<?> componentType, int... dimensions)
throws IllegalArgumentException, NegativeArraySizeException {
return multiNewArray(componentType, dimensions);
}
private static native Object multiNewArray(Class<?> componentType,
int[] dimensions)
throws IllegalArgumentException, NegativeArraySizeException;
它接受一個Class類物件,以及一個dimensions可變陣列來輸入的n維。比如建立一個二維陣列,如下程式碼所示:
public class Test {
public static void main(String args[]) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
int [][]test= (int[][]) Array.newInstance(int.class,2,2);
for (int i=0;i<test.length;i++){
for (int j=0;j<test[i].length;j++){
test[i][j]=1;
}
}
for (int i=0;i<test.length;i++){
for (int j=0;j<test[i].length;j++){
System.out.print(test[i][j]+" ");
}
System.out.println();
}
}
}
剩餘的幾個重要的方法就不一一講解了,在這裡列出來:
//獲取其陣列長度
public static native int getLength(Object array)
throws IllegalArgumentException;
//獲取指定索引的值
public static native Object get(Object array, int index)
throws IllegalArgumentException, ArrayIndexOutOfBoundsException;
//設定指定索引的值
public static native void set(Object array, int index, Object value)
throws IllegalArgumentException, ArrayIndexOutOfBoundsException;