Home IT Linux Windows Database Network Programming Server Mobile  
           
  Home \ Programming \ Java transient keyword     - Ubuntu 12.04 installation OpenCV2.4.1 and compile test (Linux)

- Ubuntu under shadowsocks configuration instructions (Linux)

- C ++ Learning Notes: references (Programming)

- Install the latest Eclipse IDE in Ubuntu (Linux)

- Unsafe reboot start (Linux)

- Digital jQuery scrolling effect (Programming)

- Apache Mina framework Practice (Programming)

- The most concise Systemd tutorial, just ten minutes (Linux)

- SQLite3 simple operation (Database)

- Using the Linux VNC service (Server)

- New experience Budgie (Budgerigar) desktop environment (Linux)

- To install and deploy PHP environment under the CentOS (Server)

- Use GNU / Linux broadcasting of television programs (Linux)

- Sorting algorithm of dichotomy (binary) insertion sort algorithm (Programming)

- How to network to share files between Windows, MAC and Linux (Linux)

- Oracle 11g creates virtual private directory RMAN-06004 ORA-00942 error handling (Database)

- Ubuntu install OpenMPI (Linux)

- Sort search algorithm Java - application examples with recursive dichotomy (Programming)

- Linux common network tools: batch scanning of nmap hosting service (Linux)

- Seven kinds of NIC binding mode Detail (Linux)

 
         
  Java transient keyword
     
  Add Date : 2017-01-08      
         
       
         
  Although it is most familiar Java, but many do not know the basics of Java, such as transient keyword previously never used before, so I do not know what its role is, do today found a pen questions about this problem is, so spend time to sort out under transient keyword used up under the posture, ado, start the following:

1. transient effects and how to use

We all know that an object which implements Serilizable the interface, the object can be serialized, java this sequence mode provides developers with a lot of convenience, we do not have a specific relationship between the sequence of the process, as long as the class implements Serilizable Interface, this class of all properties and methods are automatically serialized.

However, in the actual development process, we often encounter such a problem, some of the properties of this class need to be serialized while others attribute does not need to be serialized, for example, if a user has sensitive information (such as passwords, bank card number, etc.), for safety reasons, do not want to network operations (mainly related to the operation sequence, the sequence of the local cache is also applicable) is transmitted, the information corresponding variables can be added transient keyword. In other words, the life cycle of this field exists only in the memory of the caller will not be written to disk to persist.

In short, java of transient keyword for us to provide a convenient, you only need to implement Serilizable interface is not required prior to serialization attributes add keywords transient, serialized object, this property will not be serialized to the specified destination from a.

Example code is as follows:

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 does not serialize a variable
 * Note to read when reading data stored in the order and the order data must be consistent
 *
 * /
public class TransientTest {
    
    public static void main (String [] args) {
        
        User user = new User ();
        user.setUsername ( "abcname");
        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); // User will be written into the object 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;
    }

}

The output is:

read before Serializable:
username: abcname
password: 123456

read after Serializable:
username: abcname
password: null

The password field is null, deserialization when did not get the information from the file to.

2. transient use Summary

1) Once the transient variable is modified, the variable will no longer be a part of object persistence, can not gain access to the content of the variable in the serialization.

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

3) transient keyword is modified variables can no longer be serialized, a static variable is whether or not modified transient, not be serialized.

The third point may be some people very confused, because it was discovered before the username field in the User class plus the static keyword, the result of the program remains the same, namely, static type username read out as "abcname", which does not the third point that the contradiction? In fact is this: The third point is indeed true (whether a static variable is transient modification, not be serialized), deserialized class static variable username is the current JVM of corresponding values in static variables this value is the JVM is not deserialized drawn, I do not believe? Well, here I am to prove:

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 does not serialize a variable
 * Note to read when reading data stored in the order and the order data must be consistent
 *
 * /
public class TransientTest {
    
    public static void main (String [] args) {
        
        User user = new User ();
        user.setUsername ( "abcname");
        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); // User will be written into the object file
            os.flush ();
            os.close ();
        } Catch (FileNotFoundException e) {
            e.printStackTrace ();
        } Catch (IOException e) {
            e.printStackTrace ();
        }
        try {
            // Change the value of the username before deserialization
            User.username = "jmwang";
            
            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;
    
    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;
    }

}

Operating results as follows:

read before Serializable:
username: abcname
password: 123456

read after Serializable:
username: jmwang
password: null

This shows that deserialization is the current JVM class static variables after the username corresponding values in static variables, as modified jmwang, abcname value rather than when serialized.

3. transient Details - transient keyword is modified variables it really can not be serialized?

Consider the following 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;

/ **
 * Use @descripiton Externalizable interface
 *
 *
 * /
public class ExternalizableTest implements Externalizable {

    private transient String content = "Yes, I will be serialized, whether I was transient keyword modified";

    @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 ();
    }
}

variable content will be serialized it? Well, I have the answer output, yes, the results are:

Yes, I will be serialized, whether I was transient keyword modified

That is why, not to say that the variable type is transient keyword can not be modified later serialized yet?

We know that in Java, object serialization can be achieved by implementing the two interfaces, if the Serializable interface is implemented, then all will be serialized automatically, if the implementation is Externalizable interface, there can be no automatic sequence of the need to manually specify the variables to be serialized in writeExternal method, regardless of whether the modification is transient. Therefore, the second example of the output is initialized variable content content, not null.
     
         
       
         
  More:      
 
- Open SSH remote access service that allows Android phone Ubuntu 14.04 (Linux)
- Oracle Execute to Parse perform analytical Ratio Analysis (Database)
- C language binary tree counts words (Programming)
- Ubuntu 15.10 15.04 14.10 14.04 Install Ubuntu Tweak (Linux)
- Install Python 3.3.4 under CentOS 6.4 (Linux)
- QBit development of micro-services (Server)
- CentOS 7 source code to compile and install PHP5.6 Nginx1.7.9 and MySQL (LNMP build environment) (Server)
- Debian 7.7 Installation and Configuration (Linux)
- Spring MVC Exception Handling (Programming)
- MyCAT separate read and write to achieve MySQL Practice (Database)
- Expand an existing RAID arrays and remove the failed disk in a RAID (Linux)
- independently configurable PHP environment under CentOS6.5 (Server)
- Boost-- time and date - (1) timer library introduction (Programming)
- Automatic batch resolve dependencies problem locally installed rpm package (Linux)
- Binary search -Java achieve (Programming)
- How to use Xmanager Remote Desktop and VNC Log (Linux)
- Json data with double backslashes to a single backslash Json data processing (Programming)
- Nginx request processing (Server)
- Hadoop + Zookeeper NameNode achieve high availability (Server)
- Android Action Compendium (Programming)
     
           
     
  CopyRight 2002-2016 newfreesoft.com, All Rights Reserved.