Easy Tutorial
❮ Verilog2 Gate Delay Android Tutorial Camera ❯

This is a Chinese to English translation, please provide the English translation for this text. Do not provide any explanations or text apart from the translation.

English: ## Java transient Keyword

Category Programming Techniques

Alas, although I am most familiar with Java, I don't know many of the basic knowledge of Java. For example, I have never used the transient keyword before, so I don't know what its function is. Today, I found a question about this in the pen test, so I took some time to sort out the use of the transient keyword and increase my knowledge. Well, let's not talk nonsense, let's start below:

1. The Role and Usage of transient

We all know that as long as an object implements the Serializable interface, this object can be serialized. Java's serialization mode provides a lot of convenience for developers. We don't need to care about the specific serialization process. As long as this class implements the Serializable interface, all attributes and methods of this class will be automatically serialized.

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 safety reasons, it is not hoped to be transmitted in network operations (mainly involving serialization operations, local serialization caching is also applicable), the variables corresponding to these information can be added with the transient keyword. In other words, the lifecycle of this field only exists in the memory of the caller and will not be written to the disk for persistence.

In short, Java's transient keyword provides us with convenience. You only need to implement the Serializable interface, add the keyword transient before the attributes that do not need to be serialized, and when serializing the object, this attribute will not be serialized to the specified destination.

Example

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * @description Using the transient keyword to prevent serialization of a variable
 *        Note that when reading, the order of reading data must be consistent with the order of storing data
 *        
 * @author Alexia
 * @date  2013-10-15
 */
public class TransientTest {

    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.err.println("password: " + user.getPasswd());

        try {
            ObjectOutputStream os = new ObjectOutputStream(
                    new FileOutputStream("C:/user.txt"));
            os.writeObject(user); // Write the User object to the file
            os.flush();
            os.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            ObjectInputStream is = new ObjectInputStream(new FileInputStream(
                    "C:/user.txt"));
            user = (User) is.readObject(); // Read the User data from the stream
            is.close();

            System.out.println("\nread after Serializable: ");
            System.out.println("username: " + user.getUsername());
            System.err.println("password: " + user.getPasswd());

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException 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 is:

read before Serializable: 
username: Alexia
password: 123456

read after Serializable: 
username: Alexia
password: null

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

2. Summary of transient usage

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

2) The transient keyword can only modify variables, and cannot modify methods and classes. Note that local variables cannot be modified by the transient keyword. System.out.println("username: " + user.getUsername()); System.err.println("password: " + user.getPasswd());

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException 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() {
    return passwd;
}

public void setPasswd(String passwd) {
    this.passwd = passwd;
}

}



The result of running is:


read before Serializable: username: Alexia password: 123456

read after Serializable: username: jmwang password: null


This indicates that after deserialization, the value of the static variable username in the class is the value of the corresponding static variable in the current JVM, which is modified to jmwang, not the value at the time of serialization, Alexia.

### 3. Details of using transient — Are variables marked with the transient keyword really not serializable?

Consider the following example:

## Example


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;

/**

private transient String content = "Yes, I will be serialized, regardless of whether I am marked 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();
}

}



Will the variable content be serialized? Well, I've already output the answer, yes, the result of running is:


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

Why is this, isn't it said that after a class variable is marked with the transient keyword, it will not be serialized?

We know that in Java, object serialization can be implemented by implementing two interfaces. If the Serializable interface is implemented, all serialization will be done automatically. If the Externalizable interface is implemented, nothing can be serialized automatically, and it is necessary to manually specify the variables to be serialized in the writeExternal method, which is irrelevant to whether it is modified by transient. Therefore, the second example outputs the content of the variable content when initialized, not null.

>

Source: http://www.cnblogs.com/lanxuezaipiao/p/3369962.html

❮ Verilog2 Gate Delay Android Tutorial Camera ❯