java 反射

创建对象的方式

//创建对象1:new
//创建对象2:clone
//创建对象3:序列化(序列化会引发安全漏洞,未来将会被移除jdk)
//创建对象4:反射 动态性 字符串
public class CreateNewObj implements Cloneable{
    public void hello() {
        System.out.println("hello world");
 }
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
 }
    public static void main(String[] args) throws CloneNotSupportedException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException {
         //new和克隆
         CreateNewObj test = new CreateNewObj();
         test.hello();
         CreateNewObj clone = (CreateNewObj) test.clone();//内存中位置不一样 深度克隆和浅克隆?
         clone.hello();
         //反射
         Class cloneClass = Class.forName("reflect.CreateNewObj");
         Object o = cloneClass.newInstance();
         cloneClass.getMethod("hello").invoke(o);
    }
}

反射的应用

public class ArrayLenExtend {
    public static Object goodCopy(Object oldArray, int newLength) {
//Array类型
         Class c = oldArray.getClass();
         System.out.println(c.getName());
//元素类型
         Class componentType = c.getComponentType();
         System.out.println(componentType.getName());
//创建新数组
         Object newArray = Array.newInstance(componentType, newLength);
//拷贝
        int oldLength = Array.getLength(oldArray);
        System.arraycopy(oldArray, 0, newArray, 0, oldLength);
//返回
        return newArray;
}
    public static void main(String[] args) {
        int[] a = {1, 2, 3, 4, 5};
         a = (int[]) goodCopy(a,10);
         System.out.println(a.length);
    }
}

你可能感兴趣的:(java,反射)