Java Serialization

Posted 每天更强一点...

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java Serialization相关的知识,希望对你有一定的参考价值。

References

[1] http://java-questions.com/Serialization-interview-questions.html

[2] http://javarevisited.blogspot.co.uk/2011/04/top-10-java-serialization-interview.html

1) If a class is serializable but its superclass in not, what will be the state of the instance variables inherited from super class after deserialization?

The values of the instance variables inherited from superclass will be reset to the values they were given during the original construction of the object as the non-serializable super-class constructor will run.

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

class ChildSerializable extends ParentNonSerializable implements Serializable {
    private static final long serialVersionUID = 1L;
    String color;
    ChildSerializable() {
        this.noOfWheels = 8;
        this.color = "blue";
    }
}


class ParentNonSerializable {
    int noOfWheels;
    ParentNonSerializable() {
        this.noOfWheels = 4;
    }
}

public class SubSerialSuperNotSerial {
    public static void main(String [] args)  {
        ChildSerializable c = new ChildSerializable();
        System.out.println("Before : -  " +  c.noOfWheels + " "+ c.color);
        try {
            FileOutputStream fs = new FileOutputStream("superNotSerail.ser");
            ObjectOutputStream os = new ObjectOutputStream(fs);
            os.writeObject(c);
            os.close();
        } catch (Exception e) {  e.printStackTrace(); }
        try {
            FileInputStream fis = new FileInputStream("superNotSerail.ser");
            ObjectInputStream ois = new ObjectInputStream(fis);
            c = (ChildSerializable) ois.readObject();
            ois.close();
        } catch (Exception e) {  e.printStackTrace(); }
        System.out.println("After :-  " +  c.noOfWheels + " "+ c.color);
    }
}

Output is:

Before : - 8 blue
After :- 4 blue

If we change ParentNonSerializable to be serializable

class ParentNonSerializable implements Serializable{
    private static final long serialVersionUID = 1L;

    int noOfWheels;
    ParentNonSerializable() {
        this.noOfWheels = 4;
    }
}

Output is:

Before : - 8 blue
After :- 8 blue

2) What is use of serialVersionUID?

During object serialization, the default Java serialization mechanism writes the metadata about the object, which includes the class name, field names and types, and superclass. This class definition is stored as a part of the serialized object. This stored metadata enables the deserialization process to reconstitute the objects and map the stream data into the class attributes with the appropriate type
Everytime an object is serialized the java serialization mechanism automatically computes a hash value. ObjectStreamClass‘s computeSerialVersionUID() method passes the class name, sorted member names, modifiers, and interfaces to the secure hash algorithm (SHA), which returns a hash value.The serialVersionUID is also called suid.
So when the serilaize object is retrieved , the JVM first evaluates the suid of the serialized class and compares the suid value with the one of the object. If the suid values match then the object is said to be compatible with the class and hence it is de-serialized. If not InvalidClassException exception is thrown.

Changes to a serializable class can be compatible or incompatible. Following is the list of changes which are compatible:

Add fields
Change a field from static to non-static
Change a field from transient to non-transient
Add classes to the object tree
List of incompatible changes:

Delete fields
Change class hierarchy
Change non-static to static
Change non-transient to transient
Change type of a primitive field
So, if no suid is present, inspite of making compatible changes, jvm generates new suid thus resulting in an exception if prior release version object is used .

The only way to get rid of the exception is to recompile and deploy the application again.

If we explicitly mention the sUid using the statement:

private final static long serialVersionUID = <integer value>

then if any of the metioned compatible changes are made the class need not to be recompiled. But for incompatible changes there is no other way than to compile again.

3) While serializing you want some of the members not to serialize? How do you achieve it?

Another frequently asked Serialization interview question. This is sometime also asked as what is the use of transient variable, does transient and static variable gets serialized or not etc. so if you don‘t want any field to be part of object‘s state then declare it either static or transient based on your need and it will not be included during Java serialization process.














以上是关于Java Serialization的主要内容,如果未能解决你的问题,请参考以下文章

serialization机制

Android Serialization序列化

Java Serialization vs JSON vs XML

Java Serialization可以将对象反序列化为父类的实例

java 序列化怎么标记为不可序列化的字段?

java代码在片段活动中不起作用