transient 翻译:短暂的,转瞬即逝的;暂时的
Serilizable 接口,其属性和方法都会被自动序列化。transient 关键字修饰该属性,正如其意,transient修饰的对象只会短暂的存在于内存中。transient 只能修饰属性,不能用于类和方法。javaimport java.io.*;
// 示例1:使用 transient 修饰实例变量
class MyClass implements Serializable {
    // 正常序列化该变量
    private int normalVar = 10;
    
    // transient 修饰的变量不会被序列化
    private transient String transientVar = "Transient variable";
    
    public void display() {
        System.out.println("normalVar: " + normalVar);
        System.out.println("transientVar: " + transientVar);
    }
}
public class Main {
    public static void main(String[] args) {
        MyClass obj = new MyClass();
        obj.display();
        
        // 将对象序列化到文件
        try {
            FileOutputStream fileOut = new FileOutputStream("object.ser");
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
            out.writeObject(obj);
            out.close();
            fileOut.close();
            System.out.println("Object serialized successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        // 从文件中反序列化对象
        try {
            FileInputStream fileIn = new FileInputStream("object.ser");
            ObjectInputStream in = new ObjectInputStream(fileIn);
            MyClass newObj = (MyClass) in.readObject();
            newObj.display();
            in.close();
            fileIn.close();
            System.out.println("Object deserialized successfully.");
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
在上面的示例中,MyClass 类实现了 Serializable 接口,并包含了一个 transient 变量 transientVar。在 main 方法中,我们创建了一个 MyClass 对象并序列化到文件中,然后从文件中反序列化该对象。在对象被序列化和反序列化过程中,transientVar 变量的值被忽略,因为它被声明为 transient,所以在反序列化后,它的值为 null。
本文作者:DingDangDog
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!