Simple analysis of Java transient key words

Source: Internet
Author: User

The role of 1.transient and how to use it

We all know that an object can be serialized as long as the Serilizable interface is implemented, and the Java serialization pattern provides developers with a lot of convenience, and we don't have to relate to the process of specific serialization, as long as this class implements the Serilizable interface, All properties and methods of this class are automatically serialized.

However, in the actual development process, we often encounter such a problem, some properties of this class need to serialize, and 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 purposes, do not want to operate in the network (mainly involved in serialization operations, Local serialization cache is also applicable), the variable that corresponds to this information can be added to the transient keyword. In other words, the life cycle of this field is only stored in the caller's memory and is not persisted to disk.

In short, the Java transient keyword is convenient for us, you only need to implement the Serilizable interface, will not need to serialize the property before adding the keyword transient, when serializing the object, this property will not be serialized to the specified destination.

The example code is as follows:

ImportJava.io.FileInputStream;Importjava.io.FileNotFoundException;ImportJava.io.FileOutputStream;Importjava.io.IOException;ImportJava.io.ObjectInputStream;ImportJava.io.ObjectOutputStream;Importjava.io.Serializable;/*** @description do not serialize a variable using the transient keyword * Note that when reading, the order of reading data must be consistent with the order in which the data is stored * *@authorAlexia * @date 2013-10-15*/ Public classTransienttest { Public Static voidMain (string[] args) {User User=NewUser (); 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=NewObjectOutputStream (NewFileOutputStream ("/home/yangqianli/user.txt")); Os.writeobject (user); //write the user object into a fileOs.flush ();        Os.close (); } Catch(FileNotFoundException e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); }        Try{ObjectInputStream is=NewObjectInputStream (NewFileInputStream ("/home/yangqianli/user.txt")); User= (User) is.readobject ();//reading user data from a streamIs.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 (); }    }}classUserImplementsSerializable {Private Static Final LongSerialversionuid = 8294180014912103005L; PrivateString username; Private transientString passwd;  PublicString GetUserName () {returnusername; }         Public voidSetusername (String username) { This. Username =username; }         PublicString getpasswd () {returnpasswd; }         Public voidsetpasswd (String passwd) { This. passwd =passwd; }}

The output is:

123456null

2.transient Usage Summary

(1) In a class that implements the Serializable interface, once the variable is transient decorated, the variable is no longer part of the object persistence, and the contents of the variable cannot be accessed 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.

(3) Variables modified by the Transient keyword can no longer be serialized, and a static variable cannot be serialized regardless of whether it is transient modified.

3rd may be some people are confused, because found in the user class in the Username field with the static keyword, the program operation results are still unchanged, that is, the static type of username also read out as "Alexia", this does not contradict with the 3rd said? This is actually true: 3rd is True (a static variable cannot be serialized regardless of whether it is transient), and the value of the static variable username in the deserialized class is the value of the corresponding static variable in the current JVM. This value is not deserialized in the JVM, do not believe? Well, let's prove it next.

Consider the following example:

ImportJava.io.FileInputStream;Importjava.io.FileNotFoundException;ImportJava.io.FileOutputStream;Importjava.io.IOException;ImportJava.io.ObjectInputStream;ImportJava.io.ObjectOutputStream;Importjava.io.Serializable;/*** @description do not serialize a variable using the transient keyword * Note that when reading, the order of reading data must be consistent with the order in which the data is stored * *@authorAlexia * @date 2013-10-15*/ Public classTransienttest { Public Static voidMain (string[] args) {User User=NewUser (); 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=NewObjectOutputStream (NewFileOutputStream ("/home/yangqianli/user.txt")); Os.writeobject (user); //write the user object into a fileOs.flush ();        Os.close (); } Catch(FileNotFoundException e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); }        Try {            //change the value of username before deserializingUser.username = "Jmwang"; ObjectInputStream is=NewObjectInputStream (NewFileInputStream ("/home/yangqianli/user.txt")); User= (User) is.readobject ();//reading user data from a streamIs.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 (); }    }}classUserImplementsSerializable {Private Static Final LongSerialversionuid = 8294180014912103005L;  Public StaticString username; Private transientString passwd;  PublicString GetUserName () {returnusername; }         Public voidSetusername (String username) { This. Username =username; }         PublicString getpasswd () {returnpasswd; }         Public voidsetpasswd (String passwd) { This. passwd =passwd; }}

The result of the operation is:

123456null

This indicates 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 Alexia after the modified Jmwang instead of the value at the time of serialization.

Reasons for HashMap keyword transient in 3.Java

There is an object in HashMap transient node[] table; This is where the data is stored, but why add the keyword transient?

(1) Transient is an indication that the data is not involved in serialization. Because there is a lot of space in the array data members of the HASHMAP that are stored in the data is not used, the space that is not used is serialized without meaning. So you need to manually use the WriteObject () method to serialize only the array of actual stored elements.
(2) since different virtual machines may not have the same Code value for the same hashcode, if you use the default serialization, the position of the element is consistent with the previous one, but because the value of hashcode is not the same, the positional function IndexOf () returns an element with a different subscript, which is not the result we want.

4. Practice Small Opportunities

Only objects with classes that implement the serializable or Externalizable interface can be serialized. What is the difference between defining a transient variable in a class that implements both interfaces separately? Verified by self-test.

Result: If the serializable interface is implemented, all serialization will be performed automatically, and if it is transient decorated and not static, it is not serialized, and if the Externalizable interface is implemented, nothing can be automatically serialized. You need to manually specify the variable you want to serialize in the Writeexternal method, regardless of whether it is transient decorated.

Reference:

Http://www.cnblogs.com/lanxuezaipiao/p/3369962.html (Most of the content reproduced this blog)

Http://www.blogjava.net/fhtdy2004/archive/2009/06/20/286112.html

http://segmentfault.com/q/1010000000630486

Simple analysis of Java transient key words

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.