Java serializable in-depth understanding

Source: Internet
Author: User
Tags object object object serialization

First, the concept and purpose of serialization


1. What is serialization?
Serialization (serialization) is a concept in computer science that refers to storing objects in media (such as files, intrinsic buffers, etc.) or transmitting them over the network in a binary way. You can then re-construct an object with the same state as the original object from these contiguous bits of data through crossdress, so you can say that you have a copy in a particular case, but not all of it.
2. Why Serilzation?

In particular, serialization has three main uses: 1) as a persistence mechanism if you are using a fileoutputstream stream, the data will be automatically written to the file, 2) as a replication mechanism if you are using a ByteArrayOutputStreamStream, the data is written in an in-memory byte array. This byte array can be used to create a copy of the initial object, 3) as a communication mechanism if you are using a socket (socket) stream, the data is automatically transmitted over a network connection to another endpoint, and the program on that endpoint decides what to do.

Second, the serialization method starts from JDK1.1, the Java language provides the object serialization mechanism, in the Java.io package, the interface serialization is used as implements the object serialization the tool, only then realizes the serialization class object can be serialized.

There is no method in the serializable interface. When a class declares that it is implementing the Serializable interface, it simply indicates that the class participates in the serialization protocol and does not need to implement any special methods. Here we show you how to serialize an object by using an example.

1. Defining a Serializable Object


A class that must implement the serializable interface if it is to enable its objects to be serialized. We define a class student as follows:

[Java]View Plaincopy
  1. Import java.io.Serializable;
  2. public class Student implements Serializable {
  3. int id;//No.
  4. String name;//Name
  5. int age;//Age
  6. String Department; Department
  7. public Student (int ID, string name, Int. age, String department) {
  8. This.id = ID;
  9. THIS.name = name;
  10. This.age = age;
  11. this.department = Department;
  12. }
  13. }
2. Constructing the object's input/output stream

To serialize an object, it must be associated with a certain object output/input stream, save the state of the object through the object output stream, and restore the object state through the object input stream.

In the java.io package, ObjectInputStream and ObjectOutputStream are provided to extend the data flow capabilities to read-write objects. In ObjectInputStream, an object can be read directly using the ReadObject () method, and the object can be saved directly to the output stream using the WriteObject () method in ObjectOutputStream.

[Java]View Plaincopy
  1. Import Java.io.FileInputStream;
  2. Import Java.io.FileOutputStream;
  3. Import java.io.IOException;
  4. Import Java.io.ObjectInputStream;
  5. Import Java.io.ObjectOutputStream;
  6. public class Objectser {
  7. public static void Main (String args[]) throws IOException,
  8. classnotfoundexception {
  9. Student stu = new Student (981036, "liuming", "CSD");
  10. FileOutputStream fo = new FileOutputStream ("Data.ser");
  11. ObjectOutputStream so = new ObjectOutputStream (FO);
  12. try {
  13. So.writeobject (Stu);
  14. So.close ();
  15. } catch (IOException e) {
  16. System.out.println (e);
  17. }
  18. Stu = null;
  19. FileInputStream fi = new FileInputStream ("Data.ser");
  20. ObjectInputStream si = new ObjectInputStream (FI);
  21. try {
  22. Stu = (Student) si.readobject ();
  23. Si.close ();
  24. } catch (IOException e)
  25. {
  26. System.out.println (e);
  27. }
  28. System.out.println ("Student Info:");
  29. System.out.println ("ID:" + stu.id);
  30. System.out.println ("Name:" + stu.name);
  31. System.out.println ("Age:" + stu.age);
  32. System.out.println ("DEP:" + stu.department);
  33. }
  34. }
  35. The results of the operation are as follows:
  36. Student Info:
  37. id:981036
  38. Name:liuming
  39. Age:18
  40. Dep:csd

In this example, we first define a class student, implement the Serializable interface, and then save the student object to the file Data.ser through the WriteObject () method of the object output stream. After that, the saved student object is read from the file Data.ser through the Readobjcet () method of the home input stream. As you can see from the running results, the state of the object can be saved and restored correctly by serialization mechanism.



Iii. Considerations for serialization 1. Serialization of elements that can be saved
Serialization can only hold non-static member arguments of an object, cannot save any member methods and static member variables, and serialization saves only the value of the variable, and no modifier for the variable can be saved.
2.transient keywords

For certain types of objects whose state is instantaneous, such an object cannot save its state. For example, a thread object or a FileInputStream object, we must use the Transient keyword for these fields, otherwise the compiler will report.

In addition, serialization may involve storing objects on disk or developing data on the network, which can create security issues. Because the data is outside the Java Runtime Environment, it is not under the control of Java security. For those fields that require secrecy, they should not be stored on permanent media, or should not be saved simply and without processing, in order to ensure security. You should add the Transient keyword before these fields.

The following is an explanation of the transient keyword in the Java specification: the transient marker is not fully specified by the Java Language   Specification but was used in object serialization to mark member variables this should not Be serialized.


Here is an example of a transient application:

[Java]View Plaincopy
  1. Logginginfo.java
  2. Import Java.io.FileInputStream;
  3. Import Java.io.FileOutputStream;
  4. Import Java.io.ObjectInputStream;
  5. Import Java.io.ObjectOutputStream;
  6. Import Java.util.Date;
  7. public class LoggingInfo implements Java.io.Serializable {
  8. Private static final long serialversionuid = 1L;
  9. Private date Loggingdate = new Date ();
  10. Private String uid;
  11. private transient String pwd;
  12. LoggingInfo (string user, string password) {
  13. UID = user;
  14. PWD = password;
  15. }
  16. Public String toString () {
  17. String password = null;
  18. if (pwd = = null) {
  19. Password = "Not SET";
  20. } else {
  21. Password = pwd;
  22. }
  23. Return "Logon info: \ n" + "User:" + uid + "\ n Logging Date:"
  24. + loggingdate.tostring () + "\ n Password:" + password;
  25. }
  26. public static void Main (string[] args) {
  27. LoggingInfo loginfo = new LoggingInfo ("MIKE", "mechanics");
  28. System.out.println (Loginfo.tostring ());
  29. try {
  30. ObjectOutputStream o = new ObjectOutputStream (New FileOutputStream (
  31. "Loginfo.out"));
  32. O.writeobject (Loginfo);
  33. O.close ();
  34. } catch (Exception e) {//deal with Exception
  35. }
  36. To read the object back, we can write
  37. try {
  38. ObjectInputStream in = new ObjectInputStream (New FileInputStream (
  39. "Loginfo.out"));
  40. LoggingInfo logInfo1 = (logginginfo) in.readobject ();
  41. System.out.println (Loginfo1.tostring ());
  42. } catch (Exception e) {//deal with Exception
  43. }
  44. }
  45. }

Summarize:

Serialization consists of two parts: serialization and deserialization. Serialization is the first part of this process that decomposes data into a byte stream for storage in a file or on a network. Deserialization is the opening of a byte stream and refactoring the object. Object serialization not only converts the base data type to a byte representation, but sometimes restores the data. Recovering data requires an object instance that has recovery data. The serialization process in ObjectOutputStream is connected to a byte stream, including object type and version information. When deserializing, the JVM generates an object instance with header information and then copies the data in the object stream into the object data member

The process of serialization is that the object writes the byte stream and reads the object from the byte stream. After you convert the object state to a byte stream, you can save it to a file with various byte stream classes in the Java.io package, pipe to another thread, or send the object data to another host over a network connection. The object serialization feature is simple and powerful, with applications in RMI, sockets, JMS, and EJBs. Object serialization problem is not the most exciting topic in network programming, but it is very important and has many practical meanings.

Object serialization enables the implementation of distributed objects. Main applications For example: RMI to use object serialization to run a service on a remote host, just as you would when running an object on a local machine.

Java object serialization preserves not only the data of an object, but also the data of each object referenced by the object. You can write the entire object hierarchy to a stream of bytes that can be saved in a file or passed on a network connection. Object serialization allows you to "deep copy" the object, which is to copy the object itself and the referenced object itself. Serializing an object may get the entire sequence of objects.

Finally, some of the real-world scenarios that are often encountered, which are related to Java serialization, make it easy for readers to keep in mind some of the high-level understandings in Java serialization by analyzing the causes of the situation.

Serialization ID Issues

Scenario: Two clients A and B attempt to pass object data over the network, and the A-side serializes object C to binary data and then to B,b to deserialize to get C.

Problem: The full class path of the C object is assumed to be com.inout.Test, and there is such a class file on both A and B ends, the function code is exactly the same. The Serializable interface is also implemented, but the deserialization always indicates that it is not successful.

Workaround: Whether the virtual machine allows deserialization, not only depends on whether the classpath and function code are consistent, but one very important point is whether the serialization IDs of the two classes are consistent (that is, private static final long Serialversionuid = 1L). Two paragraphs in the same code, although the function code of the two classes is exactly the same, but the serialization IDs are different, they cannot be serialized and deserialized with one another.

The serialization ID provides two build strategies under Eclipse, one fixed 1L, one randomly generating a non-repeating long type of data (actually generated using the JDK tool), where there is a recommendation that, if there is no special requirement, it is available with the default 1L, which ensures that the code is consistent When deserialization succeeds. So what does a randomly generated serialization ID do, and sometimes it can be used to restrict the use of certain users by changing the serialization ID.

Encrypt sensitive fields

Scenario: The server sends serialized object data to the client, some data in the object is sensitive, such as the password string, and so on, in order to encrypt the password field when it is serialized, and if the client owns the decrypted key, the password can be read only when the client is deserialized. This guarantees the data security of the serialized object to a certain extent.

Workaround: During serialization, the virtual opportunity attempts to invoke the WriteObject and ReadObject methods in the object class for user-defined serialization and deserialization, and if there is no such method, the default call is ObjectOutputStream Defaultwriteobject method and the Defaultreadobject method of ObjectInputStream. The user-defined WriteObject and ReadObject methods allow the user to control the serialization process, such as the ability to dynamically change the serialized value during serialization. Based on this principle, it can be used in practical applications for cryptographic work of sensitive fields, and listing 3 shows this process.

[Java]View Plaincopy
    1. Listing 3. Static variable serialization problem code
    2. Private static final long serialversionuid = 1L;
    3. Private String Password = "Pass";
    4. Public String GetPassword () {
    5. return password;
    6. }
    7. public void SetPassword (String password) {
    8. This.password = password;
    9. }
    10. private void WriteObject (ObjectOutputStream out) {
    11. try {
    12. Putfield putfields = Out.putfields ();
    13. System.out.println ("Original password:" + password);
    14. Password = "Encryption";//Analog encryption
    15. Putfields.put ("password", password);
    16. SYSTEM.OUT.PRINTLN ("Password after encryption" + password);
    17. Out.writefields ();
    18. } catch (IOException e) {
    19. E.printstacktrace ();
    20. }
    21. }
    22. private void ReadObject (ObjectInputStream in) {
    23. try {
    24. GetField readfields = In.readfields ();
    25. Object object = Readfields.get ("Password", "");
    26. System.out.println ("String to Decrypt:" + object.tostring ());
    27. Password = "Pass";//impersonation decryption, need to get local key
    28. } catch (IOException e) {
    29. E.printstacktrace ();
    30. } catch (ClassNotFoundException e) {
    31. E.printstacktrace ();
    32. }
    33. }
    34. public static void Main (string[] args) {
    35. try {
    36. ObjectOutputStream out = new ObjectOutputStream (
    37. New FileOutputStream ("Result.obj"));
    38. Out.writeobject (New Test ());
    39. Out.close ();
    40. ObjectInputStream oin = new ObjectInputStream (New FileInputStream (
    41. "Result.obj"));
    42. Test T = (test) oin.readobject ();
    43. System.out.println ("decrypted string:" + T.getpassword ());
    44. Oin.close ();
    45. } catch (FileNotFoundException e) {
    46. E.printstacktrace ();
    47. } catch (IOException e) {
    48. E.printstacktrace ();
    49. } catch (ClassNotFoundException e) {
    50. E.printstacktrace ();
    51. }
    52. }
    53. In the WriteObject method in Listing 3, the password is encrypted, in the ReadObject, the password is decrypted, only the client with the key, can correctly parse out the password, to ensure the security of the data.

Java serializable in-depth understanding

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.