JAVA實現(xiàn)深拷貝的幾種方式代碼
準(zhǔn)備
定義兩個類用于測試拷貝,類內(nèi)容如下,目的是深拷貝一個User類的對象:
@Data @Accessors(chain = true) public class User { private Integer id; private Integer age; private String name; private Car car; private String category; }
@Data @Accessors(chain = true) public class Car { private Integer id; private String color; private String name; }
實現(xiàn)
package com.demo; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.Data; import lombok.experimental.Accessors; import java.io.*; @Data @Accessors(chain = true) public class User implements Cloneable, Serializable { private Integer id; private Integer age; private String name; private Car car; private String category; @Override public User clone() throws CloneNotSupportedException { return (User) super.clone(); } /** * 方法一:最原始的實現(xiàn)方式,通過構(gòu)造方法手創(chuàng)建 * 優(yōu)點: * 1.實現(xiàn)簡單直觀 * 2.不需要依賴額外的接口和第三方包 * 缺點: * 1.成員變量發(fā)生變動需要修改方法,不滿足開閉原則; * 2.不具有可復(fù)用性; */ public User copyUser1() { User copyUser = new User() .setId(this.getId()) .setName(this.getName()) .setAge(this.getAge()) .setCategory(this.getCategory()); if (this.getCar() != null) { copyUser.setCar(new Car().setId(this.getCar().getId()) .setColor(this.getCar().getColor()) .setName(this.getCar().getName())); } return copyUser; } /** * 方法二:使用Object的clone方法實現(xiàn) * 優(yōu)點: * 1.較方式1實現(xiàn)更簡單,不需要關(guān)注copy細(xì)節(jié); * 2.不需要依賴第三方包; * 3.不修改引用類型成員變量不需要修改代碼 * 缺點: * 1.需要實現(xiàn)Cloneable,重寫父類clone方法,不滿足里式替換; * 2.且引用類型成員變量發(fā)生變動需要修改方法,不滿足開閉原則; * 3.不具有可復(fù)用性; */ public User copyUser2() throws CloneNotSupportedException { User cloneUser = this.clone(); if(this.getCar() != null) { cloneUser.setCar(this.getCar().clone()); } return cloneUser; } /** * 方法三:使用Java自帶的流方式實現(xiàn) * 優(yōu)點: * 1.不破壞類的封裝,無需了解被copy對象的內(nèi)部 * 2.不需要依賴第三方包 * 3.代碼可復(fù)用 * 缺點: * 1.需要實現(xiàn)Serializable接口,會有額外的開銷 */ public User copyUser3() throws IOException, ClassNotFoundException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(this); ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bis); return (User) ois.readObject(); } /** * 方法四:使用第三方包Jackson實現(xiàn) * 優(yōu)點: * 1.不破壞類的封裝,無需了解被copy對象的內(nèi)部 * 2.不需要實現(xiàn)接口 * 3.代碼可復(fù)用 * 缺點: * 1.需要依賴第三方包 * 2.內(nèi)部實現(xiàn)復(fù)雜 */ public User copyUser4() throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); return objectMapper.readValue(objectMapper.writeValueAsString(this),User.class); } }
驗證
package com.demo; import java.io.IOException; public class CopyDemo { public static void main(String[] args) throws IOException, CloneNotSupportedException, ClassNotFoundException { User user = new User().setAge(10).setName("李四").setId(3).setCategory("工人"); user.setCar(new Car().setName("保時捷").setId(999).setColor("黑色")); User copyUser1 = user.copyUser1(); System.out.println("copyUser1:" + copyUser1); System.out.println("copyUser1與user對象是否是同一個:" + (System.identityHashCode(user) == System.identityHashCode(copyUser1))); System.out.println("copyUser1中的car與user中的car是否是同一個:"+(System.identityHashCode(user.getCar()) == System.identityHashCode(copyUser1.getCar()))); System.out.println("===================="); User copyUser2 = user.copyUser2(); System.out.println("copyUser2:" + copyUser2); System.out.println("copyUser2與user對象是否是同一個:" + (System.identityHashCode(user) == System.identityHashCode(copyUser2))); System.out.println("copyUser2中的car與user中的car是否是同一個:"+(System.identityHashCode(user.getCar()) == System.identityHashCode(copyUser2.getCar()))); System.out.println("===================="); User copyUser3 = user.copyUser3(); System.out.println("copyUser3:" + copyUser3); System.out.println("copyUser3與user對象是否是同一個:" + (System.identityHashCode(user) == System.identityHashCode(copyUser3))); System.out.println("copyUser3中的car與user中的car是否是同一個:"+(System.identityHashCode(user.getCar()) == System.identityHashCode(copyUser3.getCar()))); System.out.println("===================="); User copyUser4 = user.copyUser4(); System.out.println("copyUser4:" + copyUser4); System.out.println("copyUser4與user對象是否是同一個:" + (System.identityHashCode(user) == System.identityHashCode(copyUser4))); System.out.println("copyUser4中的car與user中的car是否是同一個:"+(System.identityHashCode(user.getCar()) == System.identityHashCode(copyUser4.getCar()))); } }
驗證結(jié)果
copyUser1:User(id=3, age=10, name=李四, car=Car(id=999, color=黑色, name=保時捷), category=工人)
copyUser1與user對象是否是同一個:false
copyUser1中的car與user中的car是否是同一個:false
====================
copyUser2:User(id=3, age=10, name=李四, car=Car(id=999, color=黑色, name=保時捷), category=工人)
copyUser2與user對象是否是同一個:false
copyUser2中的car與user中的car是否是同一個:false
====================
copyUser3:User(id=3, age=10, name=李四, car=Car(id=999, color=黑色, name=保時捷), category=工人)
copyUser3與user對象是否是同一個:false
copyUser3中的car與user中的car是否是同一個:false
====================
copyUser4:User(id=3, age=10, name=李四, car=Car(id=999, color=黑色, name=保時捷), category=工人)
copyUser4與user對象是否是同一個:false
copyUser4中的car與user中的car是否是同一個:false
結(jié)論
使用java原生推薦方法三,方法一、方法二缺點過于明顯,第三方庫的方式可以用方法四,spring boot默認(rèn)的序列化反序列化就是Jackson,另外比照方法四同類的類庫也能實現(xiàn)
到此這篇關(guān)于JAVA實現(xiàn)深拷貝的幾種方式的文章就介紹到這了,更多相關(guān)JAVA實現(xiàn)深拷貝內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
探索分析Redis?AOF日志與數(shù)據(jù)持久性
這篇文章主要為大家介紹了探索分析Redis?AOF日志與數(shù)據(jù)持久性詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-12-12springboot 整合fluent mybatis的過程,看這篇夠了
這篇文章主要介紹了springboot 整合fluent mybatis的過程,配置數(shù)據(jù)庫連接創(chuàng)建數(shù)據(jù)庫的詳細(xì)代碼,本文給大家介紹的非常詳細(xì),需要的朋友可以參考下2021-08-08SpringBoot項目中忽略某屬性返回數(shù)據(jù)給前端
在Spring Boot中,保護(hù)敏感信息和減少數(shù)據(jù)傳輸是很重要的,我們可以使用多種方法來忽略返回數(shù)據(jù)中的字段,無論是使用@JsonIgnore注解、Projection投影、@JsonIgnoreProperties注解還是自定義序列化器,都能達(dá)到我們的目的,在實際應(yīng)用中,根據(jù)具體場景和需求選擇合適的方法2024-05-05IDEA Maven源修改為國內(nèi)阿里云鏡像的正確方式
為了加快 Maven 依賴的下載速度,可以將 Maven 的中央倉庫源修改為國內(nèi)的鏡像,比如阿里云鏡像,以下是如何在 IntelliJ IDEA 中將 Maven 源修改為阿里云鏡像的詳細(xì)步驟,感興趣的同學(xué)可以參考閱讀一下2024-09-09java注解結(jié)合aspectj AOP進(jìn)行日志打印的操作
這篇文章主要介紹了java注解結(jié)合aspectj AOP進(jìn)行日志打印的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-02-02