[java] Notes on the use of Java transient keyword [transfer]

Reprint address: https://www.cnblogs.com/lanxuezaipiao/p/3369962.html

1. The role and usage of transient

      We all know that as long as an object implements the Serilizable interface, the object can be serialized. This serialization mode of java provides a lot of convenience for developers. We do not need to concern the specific serialization process, as long as the class implements Serilizable. interface, all properties and methods of this class are automatically serialized.

      However, in the actual development process, we often encounter such problems. Some properties of this class need to be serialized, while other properties do not need to be serialized. For example, if a user has some sensitive information (such as password, bank Card number, etc.), for the sake of security, do not want to be transmitted in network operations (mainly involving serialization operations, local serialization cache is also applicable), the variables corresponding to these information can be added with the transient keyword. In other words, the lifetime of this field only exists in the caller's memory and will not be written to disk for persistence.

      In a word, the transient keyword of java provides us with convenience. You only need to implement the Serilizable interface and add the keyword transient before the attributes that do not need to be serialized. When serializing the object, this attribute will not be serialized to the specified purpose. in the ground.

 

The sample code is as follows:

  View Code

The output is:

copy code
read before Serializable:
username: Alexia
password: 123456

read after Serializable:
username: Alexia
password: null
copy code

The password field is null, indicating that no information was obtained from the file at all during deserialization.

2. Summary of transient use

1) Once the variable is modified by transient, the variable will no longer be part of the object persistence, and the content of the variable cannot be accessed after serialization.

2) The transient keyword can only modify variables, but not methods and classes. Note that local variables cannot be modified by the transient keyword. If the variable is a user-defined class variable, the class needs to implement the Serializable interface.

3) Variables modified by the transient keyword can no longer be serialized. A static variable cannot be serialized regardless of whether it is modified by transient.

The third point may be confusing to some people, because it is found that after adding the static keyword before the username field in the User class, the program running result remains unchanged, that is, the static type of username is also read as "Alexia", which is not the same as Is there a contradiction in the third point? This is actually the case: the third point is indeed correct (a static variable cannot be serialized whether it is modified by transient or not), the value of the static variable username in the class after deserialization is the value of the corresponding static variable in the current JVM , this value is not derived from deserialization in the JVM, do not believe? Well, let me prove it:

  View Code

The running result is:

copy code
read before Serializable:
username: Alexia
password: 123456

read after Serializable:
username: jmwang
password: null
copy code

This shows that the value of the static variable username in the class after deserialization is the value of the corresponding static variable in the current JVM, which is the modified jmwang, not the serialized value Alexia.

3. Transient usage details - Can a variable modified by the transient keyword really not be serialized?

Consider the following example:

copy code
import java.io.Externalizable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;

/**
 * Use of @descripton Externalizable interface
 *
 * @author Alexia
 * @date 2013-10-15
 *
 */
public class ExternalizableTest implements Externalizable {

    private transient String content = "Yes, I will be serialized regardless of whether I am modified with the transient keyword";

    @Override
    public void writeExternal(ObjectOutput out) throws IOException {
        out.writeObject(content);
    }

    @Override
    public void readExternal(ObjectInput in) throws IOException,
            ClassNotFoundException {
        content = (String) in.readObject();
    }

    public static void main(String[] args) throws Exception {
        
        ExternalizableTest et = new ExternalizableTest();
        ObjectOutput out = new ObjectOutputStream(new FileOutputStream(
                new File("test")));
        out.writeObject(et);

        ObjectInput in = new ObjectInputStream(new FileInputStream(new File(
                "test")));
        et = (ExternalizableTest) in.readObject();
        System.out.println(et.content);

        out.close();
        in.close();
    }
}
copy code

Will the content variable be serialized? Well, I output all the answers, yes, the running result is:

Yes, I will be serialized regardless of whether I am decorated with the transient keyword

Why is this, doesn't it mean that the variables of the class cannot be serialized after being modified by the transient keyword?

      We know that in Java, the serialization of objects can be achieved by implementing two interfaces. If the Serializable interface is implemented, all serialization will be performed automatically. If the Externalizable interface is implemented, nothing can be automatically serialized. To be serialized, you need to manually specify the variable to be serialized in the writeExternal method, which has nothing to do with whether it is modified by transient. So the second example outputs the initialized content of the variable content, not null.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324970747&siteId=291194637