序列化&反序列化

ObjectOutputStream/ObjectInputStream

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class Appliction {
    public static void main(String[] args) throws IOException {
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
             ObjectOutputStream out = new ObjectOutputStream(outputStream)) {
            User user = new User("John", 28);
            out.writeObject(user);
            out.close();
            outputStream.close();
            System.err.println("==>" + outputStream.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    static class User implements Serializable {
        private String name;
        private int age;

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

        public String getName() {
            return name;
        }

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

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }
    }
}

ObjectOutputStream(outputStream):往流中写入STREAM_MAGIC和STREAM_VERSION

writeObject(Object object):在writeObject时,首先要做的是获取当前序列化对象的类信息,在获取类信息时,调用的是ObjectStreamClass的lookup方法;

results matching ""

    No results matching ""