首頁  >  文章  >  Java  >  java中的transient關鍵字有什麼作用

java中的transient關鍵字有什麼作用

王林
王林轉載
2019-11-26 10:30:283166瀏覽

java中的transient關鍵字有什麼作用

作用:

體現在將資料序列化的時候,你不想把其中的某個屬性序列化到檔案中,就需要用transient修飾,指明該屬性是一個臨時的屬性

相關java影片教學:java免費影片教學

這是學生類別:

public class Student implements Serializable {//注意:要想序列化,必须实现Serializable接口
 
    private String name;
    private Integer age;
    private transient String address;  //使用transient修饰
 
    public Student() {
    }
 
    public Student(String name, Integer age, String address) {
        this.name = name;
        this.age = age;
        this.address = address;
    }
    //Getter/Setter
}

我序列化的時候不打算將學生的地址這個屬性保存,只想保存name和age屬性,我將adress屬性用transient關鍵字修飾,下面進行序列化:

public class TestStudent {
 
    public static void main(String[] args) throws IOException {
 
        List<Student> list = new ArrayList<>();
        Student s1 = new Student("Jack", 20, "北京");
        Student s2 = new Student("Rose", 21, "上海");
        Student s3 = new Student("Hoke", 22, "深圳");
        Student s4 = new Student("Mark", 23, "天津");
        Student s5 = new Student("Json", 24, "成都");
 
        list.add(s1);
        list.add(s2);
        list.add(s3);
        list.add(s4);
        list.add(s5);
 
        //将学生信息序列化到student.txt文件中
        File file = new File("student.txt");
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
        oos.writeObject(list);
 
    }
}

下面進行反序列化,進行驗證transient的作用:

@Test
    public void test() throws IOException, ClassNotFoundException {
 
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("student.txt")));
 
        Object object = ois.readObject();
        if (object instanceof List) {
            List<Student> list = (List<Student>) object;
            list.forEach(System.out::println);
        }
    }

結果:

java中的transient關鍵字有什麼作用

#可以看到輸出結果中的address屬性值為null,沒有將值序列化進去;

java相關文章教學:java零基礎入門

#

以上是java中的transient關鍵字有什麼作用的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:csdn.net。如有侵權,請聯絡admin@php.cn刪除