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

