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.

时间: 2024-12-21 20:03:16

Java Serialization的相关文章

Java Serialization vs JSON vs XML

References: [1] http://rick-hightower.blogspot.co.uk/2014/04/which-is-faster-java-object.html [2] https://www.darkreading.com/informationweek-home/why-the-java-deserialization-bug-is-a-big-deal/d/d-id/1323237? 1. Never use Java Serialization ever, ma

Java序列化(Serialization)的理解

1.什么是序列化 Java是面向对象的编程语言,有时需要保存对象,并在下次使用时可以顺利还原该对象.由于这种需求很常见,所以Java API对此提供了支持,添加相关程序代码到标准类库中,并将保存和还原的过程称之为"对象序列化". Java SE7 文档中将与对象序列化的相关内容做了详细表述,将其称为: "Java对象序列化规范"  Java Object Serialization Specification,网址为: http://docs.oracle.com/

初探Java序列化(Serialization)

Serialization(序列化)是一种将对象以一连串的字节描述的过程:反序列化Deserialization是一种将这些字节重建成一个对象的过程.[字节流的来回转换] Java中,一切都是对象,在分布式环境中经常需要将Object从这一端网络或设备传递到另一端.这就需要有一种可以在两端传输数据的协议.Java序列化机制就是为了解决这个问题而产生. 将对象状态转换成字节流之后,可以用java.io包中各种字节流的类将其保存到文件中,管道到另一线程中或通过网络连接将对象数据发送到另一主机.对象序

Java object serialization - Tutorial

Java object serialization This tutorial explains how to use Java serialization and de-serialization Table of Contents 1. Java Serialization 2. Example 3. About this website 3.1. 4. Links and Literature 1. Java Serialization Via Java Serialization you

java 中 transient 关键字意义

译文出处:Why does Java have transient variables? java 中的 transient 关键字表明了 transient 变量不应该被序列化(transient). 参考Java Language Specification, Java SE 7 Edition, Section 8.3.1.3. transient Fields: 被 transient 标记的这些变量,表明他们是某个对象中不需要被持久状态的部分(Variables may be mark

44个JAVA代码质量管理工具(转)

1. CodePro AnalytixIt’s a great tool (Eclipse plugin) for improving software quality. It has the next key features: Code Analysis, JUnit Test Generation, JUnit Test Editor, Similar Code Analysis, Metrics, Code Coverage and Dependency Analysis.2. PMDI

Java Volatile transient 关键字

随笔-204  评论-134  文章-0  trackbacks-0 Volatile修饰的成员变量在每次被线程访问时,都强迫从主内存中重读该成员变量的值.而且,当成员变量发生变化时,强迫线程将变化值回写到主内存.这样在任何时刻,两个不同的线程总是看到某个成员变量的同一个值.     Java语言规范中指出:为了获得最佳速度,允许线程保存共享成员变量的私有拷贝,而且只当线程进入或者离开同步代码块时才与共享成员变量的原始值对比.     这样当多个线程同时与某个对象交互时,就必须要注意到要让线程及

Java远程通讯可选技术及原理

Java远程通讯可选技术及原理——转 在分布式服务框架中,一个最基础的问题就是远程服务是怎么通讯的,在Java领域中有很多可实现远程通讯的技术, 例如:RMI.MINA.ESB.Burlap.Hessian.SOAP.EJB和JMS等,这些名词之间到底是些什么关系呢,它们背后到底是基于什么原理实现的呢, 了解这些是实现分布式服务框架的基础知识,而如果在性能上有高的要求的话,那深入了解这些技术背后的机制就是必须的了, 在这篇blog中我们将来一探究竟,抛砖引玉,欢迎大家提供更多的实现远程通讯的技术

Java中的序列化

以下内容引用自http://wiki.jikexueyuan.com/project/java/serialization.html: Java提供了一种机制,叫做对象序列化,这里对象被描述成一系列包括对象的数据以及有关对象的类型和在对象中存储的数据的类型的字节. 在一个序列化的对象被写进文件之后,它能在文件中被读出并被反序列化为类型信息和表示对象的字节,并且它的数据可以被用来重新创建在内存中的对象. 最让人印象深刻的是整个过程是JVM独立的,意味着一个对象能在一个平台上序列化,并能在在一个完全