Review of Java serialization and deserialization knowledge

Java serialization and deserialization

When reviewing the basics of Java, I recalled that there was a prototype pattern that used deep copy, that is, serialization and deserialization, so I wrote this article.

Book.java

import java.io.*;

public class Book implements Serializable {
    
    
    private int id;
    private String name;
    private double price;

    public Book() {
    
    
    }

    public Book(int id, String name, double price) {
    
    
        this.id = id;
        this.name = name;
        this.price = price;
    }

    public int getId() {
    
    
        return id;
    }

    public void setId(int id) {
    
    
        this.id = id;
    }

    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    public double getPrice() {
    
    
        return price;
    }

    public void setPrice(double price) {
    
    
        this.price = price;
    }

    @Override
    public String toString() {
    
    
        return "Book{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", price=" + price +
                '}';
    }
}

ObjectStream.java

import java.io.*;

public class ObjectStream {
    
    
    public static void main(String[] args) {
    
    
        try {
    
    
            Book book = new Book(1,"Java",30);
            System.out.println(book);
            // 序列化 对象->字节流
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(book);
            // 反序列化 字节流->对象
            ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bais);
            Book bookCopy = (Book) ois.readObject();
            System.out.println(bookCopy);
        } catch (IOException e) {
    
    
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
    
    
            e.printStackTrace();
        }
    }
}

Console
Insert picture description here

Guess you like

Origin blog.csdn.net/L333333333/article/details/104020559