Home IT Linux Windows Database Network Programming Server Mobile  
           
  Home \ Programming \ Java transient keyword     - UUID in Java (Programming)

- shell script: a key optimization CentOS system (Linux)

- CentOS6 installation configuration rsh (Server)

- Difference in MySQL VARCHAR and CHAR data format (Database)

- Deployment Kubernetes manage Docker example cluster on Ubuntu (Server)

- Oracle through the alarm log view and inspect the main library, physical and snapshot standby database (Database)

- Django Web dynamic three linkage (Programming)

- Git Rebase Tutorial: Using Git Rebase turn back the clock (Linux)

- Linux foundation tutorial: how to modify the host name on CentOS or RHEL 7 (Linux)

- Android in the coordinate system and a method to obtain the coordinates (Programming)

- Linux Platform Oracle 11g Single Instance Installation Deployment Configuration Quick Reference (Database)

- Redis is installed and set up Ubuntu 14.04 from the environment under the main ssdb (Server)

- TypeScript basic grammar (Programming)

- 8 Git tips (Linux)

- Android determine the device network connection status, and determine the connection (Programming)

- MySQL 5.6 Open full query log (Database)

- Build ftp server under CentOS 6.5 (Server)

- Intrusion prevention network server security maintenance tips (Linux)

- 11G ASM disk group does not automatically handle MOUNT (Database)

- Ubuntu font settings: Using Windows Font (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:      
 
- Linux command ls (Linux)
- SSH configuration under Linux (Linux)
- Several start-up mode of Tomcat (Server)
- How to enable fbcon in Debian (Linux)
- How to install the Ruby runtime environment on Mac OS X (Linux)
- Git uses a small mind (Linux)
- CentOS 5.8 (64) Python 2.7.5 installation error resolved (Linux)
- Chrome plug-in management, online-offline installation, part of the plug presentations (Linux)
- How to contribute code on GitHub uploads (Linux)
- How to manage the time and date at systemd Linux systems (Linux)
- How Bluetooth turned off by default in Ubuntu 14.04 (Linux)
- Developing a Web server yourself (Server)
- How to install Laravel PHP framework on CentOS 7 / Ubuntu 15.04 (Server)
- Figlet use (Linux)
- [JavaScript] catch (ex) statements of ex (Programming)
- Linux script to copy the folder to all folders with the same name (Linux)
- CentOS 5.10 installed Oracle 11G R2 (Database)
- Linux common network tools: Scan routing of mtr (Linux)
- How to use Aptik to backup and restore Apps/PPAs under ubuntu (Linux)
- Using VMware vSphere Client Linux virtual machine installation CentOS6.4 system (Linux)
     
           
     
  CopyRight 2002-2016 newfreesoft.com, All Rights Reserved.