Java教程

Java Transient关键字

JavaTransient关键字用于序列化。如果将任何数据成员定义为Transient数据,则不会被序列化。
让我们举个例子,我已将一个类声明为Student,它具有三个数据成员ID,名称和年龄。如果您序列化该对象,则所有值都将被序列化,但是我不想序列化一个值,例如年龄,然后我们可以将年龄数据成员声明为Transient。

Java Transient关键字示例

在此示例中,我们创建了两个类Student和PersistExample。 Student类的age数据成员被声明为Transient,其值将不会序列化。
如果对对象进行反序列化,则将获得Transient变量的默认值。
让我们创建一个带有Transient变量的类。
import java.io.Serializable;
public class Student implements Serializable{
    int id;
    String name;
    transient int age;
    //Now it will not be serialized public Student(int id, String name,int age) {
        this.id = id;
        this.name = name;
        this.age=age;
    }
}
现在编写代码以序列化对象。
import java.io.*;
class PersistExample{
    public static void main(String args[])throws Exception{
        Student s1 =new Student(211,"ravi",22);
        //creating object
        //writing object into file FileOutputStream f=new FileOutputStream("f.txt");
        ObjectOutputStream out=new ObjectOutputStream(f);
        out.writeObject(s1);
        out.flush();
        out.close();
        f.close();
        System.out.println("success");
    }
}
输出:
success
现在编写反序列化的代码。
import java.io.*;
class DePersist{
    public static void main(String args[])throws Exception{
        ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));
        Student s=(Student)in.readObject();
        System.out.println(s.id+" "+s.name+" "+s.age);
        in.close();
    }
}
211 ravi 0
如您所见,该学生的打印年龄返回0,因为没有序列化年龄值。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4