The concept of Serializable serialization and deserialization of Java, the understandable interpretation of the function

Source: Internet
Author: User
Tags object serialization serialization throw exception

Encountered this Java Serializable serialization of this interface, we may have the following problems
A, what's called serialization and deserialization
b, the effect. Why do you want to implement this Serializable interface, which is why you want to serialize
C,serialversionuid The value of this is exactly how it is set, what is the use. Some 1L, there is a long list of numbers, confusing ING.
When I first saw this keyword Serializable, it was just like all the questions.

Before dealing with this problem, you need to know a problem first, this is more important.
This serializable interface, and the related stuff, are all in Java io.

1, serialization and deserialization concepts

Serialization: The process of converting an object to a sequence of bytes is called serialization of an object.
Deserialization: The process of reverting a sequence of bytes to an object is called deserialization of the object.

The above is a professional explanation, now to some popular explanation. When the code is running, we can see a lot of objects (the debug is created),
Can be a collection of a class of objects, a lot of object data, the data,
Some of the information we want to keep him persistent, then this serialization.
is to turn these objects in memory into a sequence of byte-describing processes.
The common thing is to become a file
I do not serialize can also save the file what ah, what impact? That's what I was asking.

2, under what circumstances need serialization

When you want to save the state of an object in memory in a file or in a database;
When you want to use sockets to transfer objects on the network;
When you want to transfer objects through RMI;

(To be honest, I may have used a database of the above several)

3, how to implement serialization

Implement the Serializable interface to

The above theories are relatively simple, the actual code below to see what this serialization is capable of, as well as the resulting bug problem.

First on the object code, flying Pig. Java

  1. Package Com.lxk.model;
  2. import java.io.Serializable;
  3. /**
  4. * @author lxk on 2017/11/1
  5. */
  6. public class Flypig implements Serializable {
  7. //private static final long serialversionuid = 1L;
  8. private static String age = "269";
  9. private String name;
  10. private String color;
  11. transient private String car;
  12. //private String Addtip;
  13. Public String getName() {
  14. return name;
  15. }
  16. Public void setName(String name) {
  17. this.name = name;
  18. }
  19. Public String getColor() {
  20. return color;
  21. }
  22. Public void setcolor(String color) {
  23. this.color = color;
  24. }
  25. Public String getcar() {
  26. return car;
  27. }
  28. Public void setcar(String car) {
  29. This.car = car;
  30. }
  31. //public String Getaddtip () {
  32. //return addtip;
  33. //}
  34. //
  35. //public void Setaddtip (String addtip) {
  36. //This.addtip = Addtip;
  37. //}
  38. @Override
  39. Public String toString() {
  40. return "flypig{" +
  41. "Name=" + name + ' \ ' +
  42. ", color= '" + color + " \" +
  43. ", car= '" + car + " \" +
  44. ", age= '" + age + " \" +
  45. //", addtip= '" + addtip + "\" +
  46. '} ';
  47. }
  48. }


Note that the code for the comment is to be used in a variety of situations for a while.

Here's the main method.

  1. Package com.lxk.test;
  2. import Com.lxk.model.FlyPig;
  3. import java.io.*;
  4. /**
  5. * Serialization Test
  6. *
  7. * @author lxk on 2017/11/1
  8. */
  9. public class serializabletest {
  10. Public static void main(string[] args) throws Exception {
  11. Serializeflypig ();
  12. Flypig Flypig = Deserializeflypig ();
  13. System.out.println (Flypig.tostring ());
  14. }
  15. /**
  16. * Serialization
  17. */
  18. private static void Serializeflypig() throws IOException {
  19. Flypig Flypig = new Flypig ();
  20. Flypig.setcolor ("Black");
  21. Flypig.setname ("Naruto");
  22. Flypig.setcar ("0000");
  23. ///ObjectOutputStream object output stream, storing Flypig object in the FlyPig.txt file of e-drive, complete serialization of the Flypig object
  24. ObjectOutputStream Oos = new ObjectOutputStream (NewFileOutputStream (new File ("D:/flypig.txt" ));
  25. Oos.writeobject (Flypig);
  26. System.out.println ("Flypig object serialization succeeded!") ");
  27. Oos.close ();
  28. }
  29. /**
  30. * Deserialization
  31. */
  32. private static Flypig deserializeflypig() throws Exception {
  33. ObjectInputStream ois = new ObjectInputStream (NewFileInputStream (new File ("D:/flypig.txt" ));
  34. Flypig person = (Flypig) ois.readobject ();
  35. System.out.println ("Flypig object deserialization succeeded!") ");
  36. return person;
  37. }
  38. }

A brief description of the above 2 classes that manipulate the file stream

ObjectOutputStream represents the object output stream:

Its writeobject (Object obj) method serializes the Obj object specified by the parameter and writes the resulting sequence of bytes to a target output stream.

ObjectInputStream represents the object input stream:

Its readobject () method reads a sequence of bytes from a source input stream, deserializes them into an object, and returns them.

How to see the operation of the actual situation.

The first kind: Come up on these code, do not move, direct run, look at the effect.

The actual running result, he will generate a file in D:/flypig.txt.

From the results of the operation, see:

1, he implements serialization and deserialization of objects.

Properties that are modified by 2,transient are not serialized. I set the Audi four-lap car missing and became null. My God.

3, you don't have to rush to say that this static variable age is also serialized. This one has to be tested separately.

Second: In order to verify that this static property can be serialized and deserialized, you can do the following.

    1. Public static void main(string[] args) throws Exception {
    2. Serializeflypig ();
    3. //flypig Flypig = Deserializeflypig ();
    4. //system.out.println (flypig.tostring ());
    5. }

When this is over, it means that you are serializing objects to a file first. This object is static variable.

Now change the value of age in the Flypig class to 26.

Then, look inside the run code and execute the result.

You can see that just 269 of the serialization is not read out. But just modified 26, if possible, should be covered by this 26, is 269.

So, come to the conclusion that this statically static property, he does not serialize.

The third type: demonstrating the role and usage of the Serialversionuid

The most violent modification, directly removes the interface of the model class implementation. The subsequent serialization and deserialization methods are then executed. Direct error.

Throw exception: Notserializableexception

This is too violent, it is not recommended to do so.

Then there is the same thing as the above, which first executes the serialization method separately. Generate files.
Then, open the property Addtip, and after that, perform the deserialization method again, to see the phenomenon.

Throw exception: Invalidclassexception details are as follows.

InvalidClassException:com.lxk.model.FlyPig;
Local class Incompatible:
Stream Classdesc Serialversionuid =-3983502914954951240,
Local class Serialversionuid = 7565838717623951575

Explain:

Because I have no definite assignment to this serialversionuid in the model, but Java is automatically assigned to me,

This value is calculated in relation to the properties of this model.

When I kept it, that is, when I serialized it, there was no such addtip attribute at that time,

So, the auto-generated serialversionuid this value,

When I deserialized the Java automatically generated this serialversionuid value is different, he throws an exception.

(You can also reverse, with ID to serialize, and then, no ID to deserialize.) is the same problem. )

Again, is the first serialization, this time, the private static final long serialversionuid = 1L; The comment for this line of code opens. The Addtip attribute is commented out first

After serialization, the property is opened and then deserialized. See what happens.

This time, code execution OK, everything is fine. Good.

What this phenomenon means to us:

Old iron, the meaning is relatively large, first of all, if you do not know what the serialization is to do, in case he really like the beginning of the database, socket transmission, RMI transmission. Although I do not know what this is to do. You have a model bean implemented this interface, you did not write this serialversionuid then in the later expansion, there may be a bug that does not know the old data, then do not fry it. Recall the above error situation. Think about all the scary, this pot who comes back?

So, there is a theory, that is, in the implementation of this serializable interface, it is necessary to give this serialversionuid assignment, is such a problem.

This explains why the Eclipse editor will need to add a value for this ID when we have just started coding, after implementing this interface. And it's a long list of numbers you don't know how to get.

The following explains how the value of this serialversionuid is set to OK.

First of all, you can not use your own to assign value, Java will give you value, but this will appear above the bug, very insecure, so, you have to manually.

So, how do I assign a value, eclipse may automatically assign you a long list of numbers. This is not necessary.

Can be simply assigned to a 1L, this is OK. This ensures that the code is consistent when the deserialization succeeds.

The values of different serialversionuid will affect the deserialization, that is, the reading of the data, you write 1L, pay attention to the larger. The computer is not case-sensitive, but, as the audience, we are to distinguish between 1 and L, so say, this value, idle nothing to move, or a version upgrade, the old data is incompatible, you do not know where the problem is ...

The following is a description of the interface Serializable from the JDK API documentation
Class by implementing the Java.io.Serializable interface to enable its serialization functionality. A
class that does not implement this interface will not be able to serialize or deserialize any of its states. The
all the subtypes of a serializable class are themselves serializable. Because implementing an interface is also indirectly equivalent to inheritance. The
serialization interface has no methods or fields and is used only to identify the semantics of serialization.

Description of the Serialversionuid
Serialization runtime is associated with each serializable class using a version number called Serialversionuid. The sequence number is used during deserialization to verify that the sender and receiver of the serialized object have loaded a serialized-compatible class for the object. If the serialversionuid of the object's class that the recipient loads differs from the version number of the corresponding sender's class, deserialization will cause invalidclassexception. A serializable class can explicitly declare its own serialversionuid by declaring a field named "Serialversionuid", which must be a static (static), final (final) long field:

If the serializable class does not explicitly declare Serialversionuid, the serialization runtime calculates the default Serialversionuid value for the class based on the various aspects of the class, as described in the Java (TM) object serialization specification. However, it is strongly recommended that all serializable classes explicitly declare the SERIALVERSIONUID value because the calculation of the default Serialversionuid has a high sensitivity to the details of the class and may vary widely depending on the compiler implementation. This can lead to unexpected invalidclassexception during deserialization. Therefore, to ensure consistency of serialversionuid values across different Java compilers, the serialization class must declare an explicit SERIALVERSIONUID value. It is also strongly recommended to use the private modifier to display the declaration Serialversionuid, if possible, because such a declaration applies only to the direct declaration class-The Serialversionuid field is not useful as an inherited member. An array class cannot declare an explicit serialversionuid, so they always have a default computed value, but the array class does not have the requirement to match the Serialversionuid value

78544505

The concept of Serializable serialization and deserialization of Java, the understandable interpretation of the function

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.