Java transient keywords Use note, transient note

Source: Internet
Author: User
Tags object serialization

Java transient keywords Use note, transient note

Ah, although I am the most familiar with Java, I don't know much about the basic knowledge of Java. For example, the transient keyword has never been used before, so I don't know what it works, I found a question about this when I did the pen test today. So I took the time to sort out the use of the transient keyword ~~~ Well, let's just talk about it. Let's start:

1. Functions and usage of transient

We all know that an object can be serialized as long as the Serilizable interface is implemented. This serialization mode of java provides developers with a lot of convenience, so we don't have to worry about the specific serialization process, as long as this class implements the Serilizable interface, all attributes and methods of this class will be automatically serialized.

However, in the actual development process, we often encounter this problem. 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 passwords and bank card numbers), the user does not want to operate on the network for security reasons (mainly involves serialization operations, and the local serialization cache is also applicable) the transient keyword can be added to the variables corresponding to the information. In other words, the lifecycle of this field only exists in the caller's memory and is not written to the disk for persistence.

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

The sample code is as follows:

1 import java. io. fileInputStream; 2 import java. io. fileNotFoundException; 3 import java. io. fileOutputStream; 4 import java. io. IOException; 5 import java. io. objectInputStream; 6 import java. io. objectOutputStream; 7 import java. io. serializable; 8 9/** 10 * @ description use the transient keyword not to serialize a variable 11 * Note that when reading, the Data Reading sequence must be consistent with the data storage sequence. 12*13 * @ author Alexia14 * @ date 2013-10-1515 */16 public class TransientTest {17 18 public static void main (String [] args) {19 20 User user = new User (); 21 user. setUsername ("Alexia"); 22 user. setPasswd ("123456"); 23 24 System. out. println ("read before Serializable:"); 25 System. out. println ("username:" + user. getUsername (); 26 System. err. println ("password:" + user. getPasswd (); 27 28 try {29 ObjectOutputStream OS = new ObjectOutputStream (30 new FileOutputStream ("C:/user.txt"); 31 OS. writeObject (user); // write the User object into the file 32 OS. flush (); 33 OS. close (); 34} catch (FileNotFoundException e) {35 e. printStackTrace (); 36} catch (IOException e) {37 e. printStackTrace (); 38} 39 try {40 ObjectInputStream is = new ObjectInputStream (new FileInputStream (41 "C:/user.txt"); 42 user = (User) is. readObject (); // read User data from the stream 43 is. close (); 44 45 System. out. println ("\ nread after Serializable:"); 46 System. out. println ("username:" + user. getUsername (); 47 System. err. println ("password:" + user. getPasswd (); 48 49} catch (FileNotFoundException e) {50 e. printStackTrace (); 51} catch (IOException e) {52 e. printStackTrace (); 53} catch (ClassNotFoundException e) {54 e. printStackTrace (); 55} 56} 57} 58 59 class User implements Serializable {60 private static final long serialVersionUID = 8294180014912103005L; 61 62 private String username; 63 private transient String passwd; 64 65 public String getUsername () {66 return username; 67} 68 69 public void setUsername (String username) {70 this. username = username; 71} 72 73 public String getPasswd () {74 return passwd; 75} 76 77 public void setPasswd (String passwd) {78 this. passwd = passwd; 79} 80 81}

Output:

1 read before Serializable: 2 username: Alexia3 password: 1234564  5 read after Serializable: 6 username: Alexia7 password: null

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

2. Summary of transient usage

1) Once a variable is modified by transient, the variable will no longer be part of Object persistence, and the variable content 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 must implement the Serializable interface.

3) variables modified by the transient keyword can no longer be serialized. A static variable cannot be serialized no matter whether it is modified by the transient or not.

Third, some people may be confused, because the program running results remain unchanged after the static keyword is added to the username field in the User class, that is, the static username is also read as "Alexia, isn't this a conflict with the third point? This is actually true: the third point is true (a static variable cannot be serialized no matter whether it is modified by transient ), in the post-deserialization class, the value of the static variable username is the value of the corresponding static variable in the current JVM. This value is obtained from non-deserialization In the JVM. Don't believe it? Okay, let me prove it:

1 import java. io. fileInputStream; 2 import java. io. fileNotFoundException; 3 import java. io. fileOutputStream; 4 import java. io. IOException; 5 import java. io. objectInputStream; 6 import java. io. objectOutputStream; 7 import java. io. serializable; 8 9/** 10 * @ description use the transient keyword not to serialize a variable 11 * Note that when reading, the Data Reading sequence must be consistent with the data storage sequence. 12*13 * @ author Alexia14 * @ date 2013-10-1515 */16 public class TransientTest {17 18 public static void main (String [] args) {19 20 User user = new User (); 21 user. setUsername ("Alexia"); 22 user. setPasswd ("123456"); 23 24 System. out. println ("read before Serializable:"); 25 System. out. println ("username:" + user. getUsername (); 26 System. err. println ("password:" + user. getPasswd (); 27 28 try {29 ObjectOutputStream OS = new ObjectOutputStream (30 new FileOutputStream ("C:/user.txt"); 31 OS. writeObject (user); // write the User object into the file 32 OS. flush (); 33 OS. close (); 34} catch (FileNotFoundException e) {35 e. printStackTrace (); 36} catch (IOException e) {37 e. printStackTrace (); 38} 39 try {40 // change the username value 41 User before deserialization. username = "jmwang"; 42 43 ObjectInputStream is = new ObjectInputStream (new FileInputStream (44 "C:/user.txt"); 45 user = (User) is. readObject (); // read User data from the stream 46 is. close (); 47 48 System. out. println ("\ nread after Serializable:"); 49 System. out. println ("username:" + user. getUsername (); 50 System. err. println ("password:" + user. getPasswd (); 51 52} catch (FileNotFoundException e) {53 e. printStackTrace (); 54} catch (IOException e) {55 e. printStackTrace (); 56} catch (ClassNotFoundException e) {57 e. printStackTrace (); 58} 59} 60} 61 62 class User implements Serializable {63 private static final long serialVersionUID = 8294180014912103005L; 64 65 public static String username; 66 private transient String passwd; 67 68 public String getUsername () {69 return username; 70} 71 72 public void setUsername (String username) {73 this. username = username; 74} 75 76 public String getPasswd () {77 return passwd; 78} 79 80 public void setPasswd (String passwd) {81 this. passwd = passwd; 82} 83 84}

The running result is:

1 read before Serializable: 2 username: Alexia3 password: 1234564  5 read after Serializable: 6 username: jmwang7 password: null

This indicates that the username value of the static variable in the Post-deserialization class is the value of the static variable corresponding to the current JVM. It is the modified jmwang instead of the value Alexia during serialization.

3. transient usage details-is it true that variables modified by the transient keyword cannot be serialized?

Consider the following example:

1 import java. io. externalizable; 2 import java. io. file; 3 import java. io. fileInputStream; 4 import java. io. fileOutputStream; 5 import java. io. IOException; 6 import java. io. objectInput; 7 import java. io. objectInputStream; 8 import java. io. objectOutput; 9 import java. io. objectOutputStream; 10 11/** 12 * @ descripiton Externalizable interface use 13*14 * @ author Alexia15 * @ date 2013-10-1516*17 */18 public class ExternalizableTest implements Externalizable {19 20 private transient String content = "yes, I will be serialized, whether or not I have been modified by the transient keyword "; 21 22 @ Override23 public void writeExternal (ObjectOutput out) throws IOException {24 out. writeObject (content); 25} 26 27 @ Override28 public void readExternal (ObjectInput in) throws IOException, 29 ClassNotFoundException {30 content = (String) in. readObject (); 31} 32 33 public static void main (String [] args) throws Exception {34 35 ExternalizableTest et = new ExternalizableTest (); 36 ObjectOutput out = new ObjectOutputStream (new FileOutputStream (37 new File ("test"); 38 out. writeObject (et); 39 40 ObjectInput in = new ObjectInputStream (new FileInputStream (new File (41 "test"); 42 et = (ExternalizableTest) in. readObject (); 43 System. out. println (et. content); 44 45 out. close (); 46 in. close (); 47} 48}

Will the content Variable be serialized? Okay, I output all the answers. Yes, the running result is:

Yes, I will be serialized, whether or not I have been modified by the transient keyword

Why? Isn't the class variable serialized after being modified by the transient keyword?

We know that in Java, Object serialization can be implemented through 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. 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. Therefore, the second example outputs the content initialized by the variable content instead of null.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.