欧美亚洲中文,在线国自产视频,欧洲一区在线观看视频,亚洲综合中文字幕在线观看

      1. <dfn id="rfwes"></dfn>
          <object id="rfwes"></object>
        1. 站長(zhǎng)資訊網(wǎng)
          最全最豐富的資訊網(wǎng)站

          java中的transient關(guān)鍵字有什么作用

          java中的transient關(guān)鍵字有什么作用

          作用:

          體現(xiàn)在將數(shù)據(jù)序列化的時(shí)候,你不想把其中的某個(gè)屬性序列化到文件中,就需要用transient修飾,指明該屬性是一個(gè)臨時(shí)的屬性

          相關(guān)java視頻教程:java免費(fèi)視頻教程

          這是一個(gè)學(xué)生類:

          public class Student implements Serializable {//注意:要想序列化,必須實(shí)現(xiàn)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 }

          我序列化的時(shí)候不打算將學(xué)生的地址這個(gè)屬性保存,只想保存name和age屬性,我將adress屬性用transient關(guān)鍵字修飾,下面進(jìn)行序列化:

          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);           //將學(xué)生信息序列化到student.txt文件中         File file = new File("student.txt");         ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));         oos.writeObject(list);       } }

          下面進(jìn)行反序列化,進(jìn)行驗(yàn)證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);         }     }

          結(jié)果:

          java中的transient關(guān)鍵字有什么作用

          可以看到輸出結(jié)果中的address屬性值為null,沒有將值序列化進(jìn)去;

          java相關(guān)文章教程:java零基礎(chǔ)入門

          贊(0)
          分享到: 更多 (0)
          網(wǎng)站地圖   滬ICP備18035694號(hào)-2    滬公網(wǎng)安備31011702889846號(hào)