Java創建對象的幾種方式

總結:

java 創建對象的方式有四種:

  1. 通過 new 的方式創建 。

  2. 通過反射獲取類的構造方法,生成對象

  3. 克隆,通過已經生成的對象,克隆出一個新的對象,但是類必須要實現Cloneable,並且重寫 clone()方法。

  4. 序列化: 通過序列化已經生成的bean,在將其反序列化生成新的bean。

其中克隆,序列化需要依賴於已經生成的對象。

示例如下:

Bean.java :


import java.io.Serializable;


public class Bean implements Serializable,Cloneable{
    private static final long serialVersionUID = 1L;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

}

測試類:

public class Test {

    public static void main(String[] args) throws Exception{
        // 通過 new 獲取
        Bean bean = new Bean();
        System.out.println("bean:" + bean.hashCode());

        // 通過反射創建
        Constructor<Bean> constructor = Bean.class.getDeclaredConstructor();
        constructor.setAccessible(true);
        Bean reflex = constructor.newInstance();
        System.out.println("reflex:"+reflex.hashCode());

        // 通過克隆創建
        Bean cBean = (Bean) bean.clone();
        System.out.println("clone:"+cBean.hashCode());

        //通過序列化,反序列化獲取
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(bean);
        ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
        ObjectInputStream ois = new ObjectInputStream(bis);
        Bean serialize = (Bean) ois.readObject();
        if (ois != null)    ois.close();
        if (bis != null) bis.close();
        if (oos != null) oos.close();
        if (bos != null) bos.close();
        System.out.println("serialize:"+serialize.hashCode());

    }

}

打印結果:

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章