java 泛型,java序列化與深度克隆

 2023-11-19 阅读 22 评论 0

摘要:如果類的成員變量比較復雜,例如引用了多個可變引用類型,那么這時使用clone()方法來克隆是非常麻煩的 可以考慮序列化的方法完成克隆 java 泛型。 test代碼 package com.mingrisoft; import java.io.FileInputStream; import java.io.FileNotFound

如果類的成員變量比較復雜,例如引用了多個可變引用類型,那么這時使用clone()方法來克隆是非常麻煩的

可以考慮序列化的方法完成克隆

java 泛型。

test代碼

package com.mingrisoft;


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;


public class Test {
? ? public static void main(String[] args) {
? ? ? ? System.out.println("序列化之前:");
? ? ? ? Address address = new Address("中國", "吉林", "長春");// 創建address對象
? ? ? ? Employee employee1 = new Employee("張XX", 30, address);// 創建employee1對象
? ? ? ? System.out.println("員工1的信息:");
? ? ? ? System.out.println(employee1);// 輸出employee1對象
? ? ? ? System.out.println("序列化之后:");
? ? ? ? ObjectOutputStream out = null;
? ? ? ? ObjectInputStream in = null;
? ? ? ? Employee employee2 = null;
? ? ? ? try {
? ? ? ? ? ? out = new ObjectOutputStream(new FileOutputStream("employee.dat"));
? ? ? ? ? ? out.writeObject(employee1);// 將對象寫入到本地文件中
? ? ? ? ? ? in = new ObjectInputStream(new FileInputStream("employee.dat"));
? ? ? ? ? ? employee2 = (Employee) in.readObject();// 從本地文件讀取對象
? ? ? ? } catch (FileNotFoundException e) {
? ? ? ? ? ? e.printStackTrace();
? ? ? ? } catch (IOException e) {
? ? ? ? ? ? e.printStackTrace();
? ? ? ? } catch (ClassNotFoundException e) {
? ? ? ? ? ? e.printStackTrace();
? ? ? ? } finally {
? ? ? ? ? ? if (in != null) {
? ? ? ? ? ? ? ? try {
? ? ? ? ? ? ? ? ? ? in.close();// 關閉輸入流
? ? ? ? ? ? ? ? } catch (IOException e) {
? ? ? ? ? ? ? ? ? ? e.printStackTrace();
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? ? ? if (out != null) {
? ? ? ? ? ? ? ? try {
? ? ? ? ? ? ? ? ? ? out.close();// 關閉輸出流
? ? ? ? ? ? ? ? } catch (IOException e) {
? ? ? ? ? ? ? ? ? ? e.printStackTrace();
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? }


? ? ? ? if (employee2 != null) {
? ? ? ? ? ? employee2.getAddress().setState("中國"); // 修改員工地址
? ? ? ? ? ? employee2.getAddress().setProvince("四川"); // 修改員工地址
? ? ? ? ? ? employee2.getAddress().setCity("成都"); // 修改員工地址
? ? ? ? ? ? employee2.setName("李XX"); // 修改員工名字
? ? ? ? ? ? employee2.setAge(24);// 修改員工年齡
? ? ? ? ? ? System.out.println("員工1的信息:");
? ? ? ? ? ? System.out.println(employee1);// 輸出employee1對象
? ? ? ? ? ? System.out.println("員工2的信息:");
? ? ? ? ? ? System.out.println(employee2);// 輸出employee2對象
? ? ? ? }


? ? }


}

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/2/183438.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息