Why does Java have transient fields?

前端 未结 15 1983
旧时难觅i
旧时难觅i 2020-11-22 03:54

Why does Java have transient fields?

15条回答
  •  鱼传尺愫
    2020-11-22 04:25

    Simplified example code for transient-keyword.

    import java.io.*;
    
    class NameStore implements Serializable {
        private String firstName, lastName;
        private transient String fullName;
    
        public NameStore (String fName, String lName){
            this.firstName = fName;
            this.lastName = lName;
            buildFullName();
        }
    
        private void buildFullName() {
            // assume building fullName is compuational/memory intensive!
            this.fullName = this.firstName + " " + this.lastName;
        }
    
        public String toString(){
            return "First Name : " + this.firstName
                + "\nLast Name : " + this.lastName
                + "\nFull Name : " + this.fullName;
        }
    
        private void readObject(ObjectInputStream inputStream)
                throws IOException, ClassNotFoundException
        {
            inputStream.defaultReadObject();
            buildFullName();
        }
    }
    
    public class TransientExample{
        public static void main(String args[]) throws Exception {
            ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream("ns"));
            o.writeObject(new NameStore("Steve", "Jobs"));
            o.close();
    
            ObjectInputStream in = new ObjectInputStream(new FileInputStream("ns"));
            NameStore ns = (NameStore)in.readObject();
            System.out.println(ns);
        }
    }
    

提交回复
热议问题