The use of Java transient keyword, with learning experience

However, in the actual development process, we often encounter such problems. Some attributes of this class need to be serialized, while other attributes do not need to be serialized. For example, if a user has some sensitive information (such as password, bank card number, etc.), for security reasons, we do not want to operate on the network (mainly involving serialization), If the 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 is only stored in the caller's memory and will not be written to disk for persistence.

In short, the transient keyword of java provides us with convenience. You only need to implement the serializable interface and add the keyword transient before the attribute that does not need to be serialized. When serializing an object, this attribute will not be serialized to the specified destination.

An example code is as follows:

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

import java.io.Serializable;



/**

 * Using the transient keyword does not serialize a variable

 * Note that when reading, the order of reading data must be consistent with the order of storing data

 */

public class TransientTest {

    static String PATH = "F:/user.txt";



    public static void main(String[] args) {



        User user = new User();

        user.setUsername("Alexia");

        user.setPasswd("123456");



        System.out.println("read before Serializable: ");

        System.out.println("username: " + user.getUsername());

        System.out.println("password: " + user.getPasswd());



        try {

            ObjectOutputStream os = new ObjectOutputStream(

                    new FileOutputStream(PATH));

            os.writeObject(user); // Write User object to file

            os.flush();

            os.close();

        } catch (IOException e) {

            e.printStackTrace();

        }

        try {

            ObjectInputStream is =

                    new ObjectInputStream(new FileInputStream(PATH));

            user = (User) is.readObject(); // Read User's data from stream

            is.close();



            System.out.println("\nread after Serializable: ");

            System.out.println("username: " + user.getUsername());

            System.out.println("password: " + user.getPasswd());



        } catch (ClassNotFoundException | IOException e) {

            e.printStackTrace();

        }

    }

}



class User implements Serializable {

    private static final long serialVersionUID = 8294180014912103005L;  



    private String username;

    private transient String passwd;



    public String getUsername() {

        return username;

    }



    public void setUsername(String username) {

        this.username = username;

    }



    public String getPasswd() {

        return passwd;

    }



    public void setPasswd(String passwd) {

        this.passwd = passwd;

    }

}

Output results:

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

2. Summary of transient use

1) The variable modified by the transient keyword cannot be serialized. The variable will no longer be a part of object persistence. The content of the variable cannot be obtained through deserialization after serialization.

2) The transient keyword can only modify variables, 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) A static variable cannot be serialized whether it is modified by transient or not.

Third, some people may be confused because they find that after adding the static keyword to the username field in the User class, the program running result remains unchanged, that is, the username of static type is also read as "Alexia". Isn't this inconsistent with the third point? In fact, it is like this: the third point is true (a static variable cannot be serialized whether it is modified by transient or not). After deserialization, the value of the static variable username in the class is the value of the corresponding static variable in the current JVM. This value is derived from the JVM, not from deserialization. Don't believe it? Well, let me prove:

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

import java.io.Serializable;



public class TransientTest {

    static String PATH = "F:/user.txt";



    public static void main(String[] args) {



        User user = new User();

        user.setUsername("Alexia");

        user.setPasswd("123456");



        System.out.println("read before Serializable: ");

        System.out.println("username: " + user.getUsername());

        System.out.println("password: " + user.getPasswd());



        try {

            ObjectOutputStream os = new ObjectOutputStream(

                    new FileOutputStream(PATH));

            os.writeObject(user); // Write User object to file

            os.flush();

            os.close();

        } catch (IOException e) {

            e.printStackTrace();

        }



        try {

            // Change the value of username before deserialization

            User.username = "jmwang";



            ObjectInputStream is =

                    new ObjectInputStream(new FileInputStream(PATH));

            user = (User) is.readObject(); // Read User's data from stream

            is.close();



            System.out.println("\nread after Serializable: ");

            System.out.println("username: " + user.getUsername());

            System.out.println("password: " + user.getPasswd());



        } catch (ClassNotFoundException | IOException e) {

            e.printStackTrace();

        }

    }

}



class User implements Serializable {

    private static final long serialVersionUID = 8294180014912103005L;  



    public static String username;

    private transient String passwd;



    public String getUsername() {

        return username;

    }



    public void setUsername(String username) {

        this.username = username;

    }



    public String getPasswd() {
#### summary

It is still difficult to ask in this interview. It is required to write and run the code on the spot. It is also very important to investigate the code written by the interviewer
 because Android The knowledge system is relatively large and complex, involving all aspects of the field of computer knowledge.**Here, some of my friends and I have specially sorted out a quick upgrade for Android Systematic and comprehensive learning materials for senior engineers. Covered Android Primary—— Android Some necessary learning skills for advanced architects.**

Attached: We collected 20 sets of first and second tier Internet companies because of autumn recruitment Android Real interview questions (including BAT,Xiaomi, Huawei, meituan, Didi) and I sort it out Android Review notes (including Android Basic knowledge points Android Expand knowledge points Android Source code analysis, design pattern summary Gradle Summary of knowledge points and common algorithm problems.)
![](https://img-blog.csdnimg.cn/img_convert/4751e4d1c7abe41f7e66927ee4fbee1c.png)
**It contains self-study programming routes and interview questions in different directions/Face by face, and a series of technical articles, resources are constantly updated**

**[CodeChina Open source projects:< Android Summary of study notes+Mobile architecture video+Real interview questions for large factories+Project practice source code](https://codechina.csdn.net/m0_60958482/android_p7)**

Set of 20 sets of first and second tier Internet companies Android Real interview questions (including BAT,Xiaomi, Huawei, meituan, Didi) and I sort it out Android Review notes (including Android Basic knowledge points Android Expand knowledge points Android Source code analysis, design pattern summary Gradle Summary of knowledge points and common algorithm problems.)
[External chain picture transfer...(img-RwD6bWFE-1630668388192)]
**It contains self-study programming routes and interview questions in different directions/Face by face, and a series of technical articles, resources are constantly updated**

**[CodeChina Open source projects:< Android Summary of study notes+Mobile architecture video+Real interview questions for large factories+Project practice source code](https://codechina.csdn.net/m0_60958482/android_p7)**

Tags: Java Android Design Pattern

Posted on Sat, 04 Sep 2021 00:14:15 -0400 by jasonX