Java序列与反序列实现深度复制

在 Java 语言里深复制一个对象,常常可以先使对象实现 Serializable 接口,然后把对
象(实际上只是对象的一个拷贝)写到一个流里,再从流里读出来,便可以重建对象。

import org.apache.commons.io.output.ByteArrayOutputStream;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.*;

/**
 * @Author: thunder
 * @Date: 2020/8/5 15:49
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestClone {

    public static void main(String[] args) throws IOException, ClassNotFoundException {

        User user    =  new User("thunder","123456");
        //将对象序列化到流里
        //字节数组输出流在内存中创建一个字节数组缓冲区,所有发送到输出流的数据保存在该字节数组缓冲区中
        ByteArrayOutputStream os = new ByteArrayOutputStream();//定义字节数组输出流,向内存字节数组缓存区写数据
        ObjectOutputStream oos   = new ObjectOutputStream(os);//对象输入流,将对象转换成字节序列,然后将字节序列发送到字节数组输出流
        oos.writeObject(user);
        //将流反序列化成对象
        ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());//字节数组输入流,从内存字节数组缓冲区读取数据
        ObjectInputStream ois   = new ObjectInputStream(is);//读取输入流的数据,转化成对象
        User otheruser              = (User) ois.readObject();
        System.out.println(user);
        System.out.println(otheruser);
    }

}

class User implements Serializable{

    private static final long serialVersionUID = -1527460015361896302L;

    private String     name;
    private String     passwd;

    public User(String name, String passwd) {
        this.name   = name;
        this.passwd = passwd;
    }

}

猜你喜欢

转载自blog.csdn.net/u011582840/article/details/107820627