Why does Java have transient fields?

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

Why does Java have transient fields?

相关标签:
15条回答
  • 2020-11-22 04:31

    Before understanding the transient keyword, one has to understand the concept of serialization. If the reader knows about serialization, please skip the first point.

    What is serialization?

    Serialization is the process of making the object's state persistent. That means the state of the object is converted into a stream of bytes to be used for persisting (e.g. storing bytes in a file) or transferring (e.g. sending bytes across a network). In the same way, we can use the deserialization to bring back the object's state from bytes. This is one of the important concepts in Java programming because serialization is mostly used in networking programming. The objects that need to be transmitted through the network have to be converted into bytes. For that purpose, every class or interface must implement the Serializable interface. It is a marker interface without any methods.

    Now what is the transient keyword and its purpose?

    By default, all of object's variables get converted into a persistent state. In some cases, you may want to avoid persisting some variables because you don't have the need to persist those variables. So you can declare those variables as transient. If the variable is declared as transient, then it will not be persisted. That is the main purpose of the transient keyword.

    I want to explain the above two points with the following example:

    package javabeat.samples;
    
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.io.Serializable;
    
    class NameStore implements Serializable{
        private String firstName;
        private transient String middleName;
        private String lastName;
    
        public NameStore (String fName, String mName, String lName){
            this.firstName = fName;
            this.middleName = mName;
            this.lastName = lName;
        }
    
        public String toString(){
            StringBuffer sb = new StringBuffer(40);
            sb.append("First Name : ");
            sb.append(this.firstName);
            sb.append("Middle Name : ");
            sb.append(this.middleName);
            sb.append("Last Name : ");
            sb.append(this.lastName);
            return sb.toString();
        }
    }
    
    public class TransientExample{
        public static void main(String args[]) throws Exception {
            NameStore nameStore = new NameStore("Steve", "Middle","Jobs");
            ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream("nameStore"));
            // writing to object
            o.writeObject(nameStore);
            o.close();
    
            // reading from object
            ObjectInputStream in = new ObjectInputStream(new FileInputStream("nameStore"));
            NameStore nameStore1 = (NameStore)in.readObject();
            System.out.println(nameStore1);
        }
    }
    

    And the output will be the following:

    First Name : Steve
    Middle Name : null
    Last Name : Jobs
    

    Middle Name is declared as transient, so it will not be stored in the persistent storage.

    Source

    0 讨论(0)
  • 2020-11-22 04:31

    Simply put, the transient java keyword protect fields from the been Serialize as their non-transient fields counter parts.

    In this code snippet our abstract class BaseJob implement Serializable interface, we extends from BaseJob but we need not serialize the remote and local data sources; serialize only organizationName and isSynced fields.

    public abstract class BaseJob implements Serializable{
       public void ShouldRetryRun(){}
    }
    
    public class SyncOrganizationJob extends BaseJob {
    
       public String organizationName;
       public Boolean isSynced
    
       @Inject transient RemoteDataSource remoteDataSource;
       @Inject transient LocalDaoSource localDataSource;
    
       public SyncOrganizationJob(String organizationName) {
         super(new 
             Params(BACKGROUND).groupBy(GROUP).requireNetwork().persist());
    
          this.organizationName = organizationName;
          this.isSynced=isSynced;
    
       }
    }
    
    0 讨论(0)
  • 2020-11-22 04:33

    As per google transient meaning == lasting only for a short time; impermanent.

    Now if you want to make anything transient in java use transient keyword.

    Q: where to use transient?

    A: Generally in java we can save data to files by acquiring them in variables and writing those variables to files, this process is known as Serialization. Now if we want to avoid variable data to be written to file, we would make that variable as transient.

    transient int result=10;
    

    Note: transient variables cannot be local.

    0 讨论(0)
  • 2020-11-22 04:40

    A transient variable is a variable that may not be serialized.

    One example of when this might be useful that comes to mind is, variables that make only sense in the context of a specific object instance and which become invalid once you have serialized and deserialized the object. In that case it is useful to have those variables become null instead so that you can re-initialize them with useful data when needed.

    0 讨论(0)
  • 2020-11-22 04:43

    My small contribution :

    What is a transient field?
    Basically, any field modified with the transient keyword is a transient field.

    Why are transient fields needed in Java?
    The transient keyword gives you some control over the serialization process and allows you to exclude some object properties from this process. The serialization process is used to persist Java objects, mostly so that their states can be preserved while they are transferred or inactive. Sometimes, it makes sense not to serialize certain attributes of an object.

    Which fields should you mark transient?
    Now we know the purpose of the transient keyword and transient fields, it's important to know which fields to mark transient. Static fields aren't serialized either, so the corresponding keyword would also do the trick. But this might ruin your class design; this is where the transient keyword comes to the rescue. I try not to allow fields whose values can be derived from others to be serialized, so I mark them transient. If you have a field called interest whose value can be calculated from other fields (principal, rate & time), there is no need to serialize it.

    Another good example is with article word counts. If you are saving an entire article, there's really no need to save the word count, because it can be computed when article gets "deserialized." Or think about loggers; Logger instances almost never need to be serialized, so they can be made transient.

    0 讨论(0)
  • 2020-11-22 04:43

    A field which is declare with transient modifier it will not take part in serialized process. When an object is serialized(saved in any state), the values of its transient fields are ignored in the serial representation, while the field other than transient fields will take part in serialization process. That is the main purpose of the transient keyword.

    0 讨论(0)
提交回复
热议问题