Java transient关键字学习

568 阅读1分钟

今天在看LinkedList源码时,看到其使用transient来修饰Node变量。

下面我们就来简单学习下transient的作用和用法

transient作用

Java提供了Serilizable接口,只要实现该接口,对象就可以被自动序列化。 实际开发中,有时我们不希望对类的所有变量都序列化,就可以使用transient关键字来修饰变量。

public class SerializableClass implements Serializable {
    public static String tag = "Serializable transient Test";
    public String name;
    public int age;
    public transient int salary = 10;
    public final transient String id = "110000202001011111";
    public Account account;
}
public class Account implements Serializable {
    public String bankId;
}
Account account = new Account();
account.bankId = "1234567890";

SerializableClass serial = new SerializableClass();
serial.name = "testSerializable";
serial.age = 30;
serial.salary = 30;
serial.account = account;
File file = new File("test.info");
FileOutputStream os = null;
ObjectOutputStream oos = null;
try {
    os = new FileOutputStream(file);
    oos = new ObjectOutputStream(os);
    oos.writeObject(object);
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (oos != null) {
        try {
            oos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    if (os != null) {
        try {
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

SerializableClass.tag = "JVM Serializable transient Test";

FileInputStream is = null;
ObjectInputStream ois = null;
try {
    is = new FileInputStream(file);
    ois = new ObjectInputStream(is);
    Object obj = ois.readObject();
    SerializableClass serialread = (SerializableClass)obj;
     if (serialread != null) {
        System.out.println(serialread.name + " " + serialread.salary);
    }
    System.out.println("tag=" + SerializableClass.tag);
    if (serialread.account != null) {
        System.out.println(serialread.account.bankId);
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} catch (ClassNotFoundException e) {
    e.printStackTrace();
} finally {
    if (ois != null) {
        try {
            ois.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    if (is != null) {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
// 输出结果
name=testSerializable id=110000202001011111 salary=0
tag=JVM Serializable transient Test
bankId=1234567890
  • 未使用transient关键字修饰的变量,被序列化了。
  • 使用transient关键字修饰的变量,没有被序列化。
  • 使用final transient关键字修饰的常量,也被序列化了。
  • 一个静态变量不管是否被transient修饰,均不能被序列化。

参考

www.cnblogs.com/lingyejun/p… www.jianshu.com/p/2911e5946…