transient关键字

当使用Serializable接口实现序列化操作时,如果一个对象中的某个属性不希望被序列化,

则可以使用transient关键字进行声明:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;

class Person implements Serializable {
    private transient String name;
    private int age;

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

    public String toString() {
        return "NAME: " + this.name + ": AGE: " + this.age;
    }
}

public class SerDemo01 {
    public static void main(String[] args) throws Exception {
        ser();
        dser();
    }

    public static void ser() throws Exception {
        File f = new File("F:" + File.separator + "watasi.txt");
        ObjectOutputStream oos = null;
        OutputStream out = new FileOutputStream(f);
        oos = new ObjectOutputStream(out);
        oos.writeObject(new Person("frank", 30));
        oos.close();
    }

    public static void dser() throws Exception {
        File f = new File("F:" + File.separator + "watasi.txt");
        ObjectInputStream ois = null;
        InputStream input = new FileInputStream(f);
        ois = new ObjectInputStream(input);
        Object obj = ois.readObject();
        ois.close();
        System.out.println(obj);
    }
}

原文地址:https://www.cnblogs.com/vonk/p/3927532.html