Java-Serialisierung und -Deserialisierung
Bei der Überprüfung der Grundlagen von Java erinnerte ich mich daran, dass es ein Prototypmuster gab, das Deep Copy verwendete, dh Serialisierung und Deserialisierung, und schrieb diesen Artikel.
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();
}
}
}
Konsole