Java核心技术卷
反射这一小节难度较大
今天学习的是 Array 的copyOf方法
package reflection.arrays;
import java.awt.*;
import java.lang.reflect.Array;
import java.util.Arrays;
public class CopyOfT {
public static void main(String[] args){
int[] a ={1, 2 , 3};
// 因为newArray 是Object类型 所以需要根据 源数组类型来进行强转
a = (int[]) goodCopyOf(a , 10);
System.out.println(Arrays.toString(a));
String[] b = {"tom" , "jack" , "harry"};
b = (String[]) goodCopyOf(b , 10);
System.out.println(Arrays.toString(b));
System.out.println("generate a exception");
b = (String[]) badCopyOf(b , 10);
// System.out.println(goodCopyOf().);
}
public static Object[] badCopyOf(Object[] a,int newLength){
Object[] newArray = new Object[newLength];
//src:源对象 srcPos原数组中的起始位置 dest 目标数组对象 dest 目标数组中的起始位置 length 要拷贝的数组元素的数量
System.arraycopy(a ,0 ,newArray , 0 ,Math.min(a.length , newLength));
return newArray;
}
public static Object goodCopyOf(Object a,int newLength){
Class c1 = a.getClass();
if(!c1.isArray())
return null;
// getComponentType 是class的方法
Class componentType = c1.getComponentType(); //对象是数组类,才能调用这个方法
// System.out.println(componentType);
int length = Array.getLength(a);
//newIntance弱类型 效率低 只能调用无参构造
// new 强类型 相对高效 能调用任何public构造
Object newArray = Array.newInstance(componentType,newLength);
// System.out.println(Arrays.toString((int[]) newArray));
// System.out.println(Arrays.toString((String[]) newArray));
//src:源对象 srcPos原数组中的起始位置 dest 目标数组对象 dest 目标数组中的起始位置 length 要拷贝的数组元素的数量
System.arraycopy(a ,0 ,newArray , 0 ,Math.min(length , newLength));
return newArray;
}
}
采用 Math.min() 防止System.arraycopy拷贝的数量超过数组的最大容量 返回的是目标数组
copyOf(original,length) System.arraycopy(src,srcPos,dest,destPos,length)