Disadvantage of Serializable

  1. A major cost of implementing Serializable is that it decreases the flexibility to change a class's implementation once it has been released.

    If you accept the default serialized form, the class's private and package-private instance fields become part of its exported API, and the practice of minimizing access to fields (Item 13) loses its effectiveness as a tool for information hiding.

    It is possible to change the internal representation while maintaining the original serialized form (using

    ObjectOutputStream.putFields and ObjectInputStream.readFields ), but it can be difficult and leaves visible warts in the source code.

    stream unique identifiers (serial version UIDs)

    If you do not specify this number explicitly by declaring a static final long field named serialVersionUID , the system automatically generates it at runtime by applying a complex procedure to the class.

    The automatically generated value is affected by the class's name, the names of the interfaces it implements, and all of

    its public and protected members. If you fail to declare an explicit serial version UID, compatibility will be broken, resulting in an InvalidClassException at runtime.

  2. A second cost of implementing Serializable is that it increases the likelihood of bugs and security holes.

    Objects are created using constructors; serialization is an extralinguistic mechanism for creating objects. Relying on the default deserialization mechanism can easily leave objects open to invariant corruption and illegal access (Item 76).

  3. A third cost of implementing Serializable is that it increases the testing burden associated with releasing a new version of a class.

    When a serializable class is revised, it is important to check that it is possible to serialize an instance in the new release and deserialize it in old releases, and vice versa.

Principle

  1. Classes designed for inheritance (Item 17) should rarely implement Serializable, and interfaces should rarely extend it.
  2. If the class has invariants that would be violated if its instance fields were initialized to their default values (zero for integral types, false for boolean, and null for object reference types), you must add this readObjectNoData method to the class.

    // readObjectNoData for stateful extendable serializable classes

    private void readObjectNoData() throws InvalidObjectException {

    throw new InvalidObjectException("Stream data required");

    }

If a class that is designed for inheritance is not serializable, it may be impossible to write a serializable subclass. Specifically, it will be impossible if the superclass does not provide an accessible parameterless constructor.

You should consider providing a parameterless constructor on nonserializable classes designed for inheritance .

// Nonserializable stateful class allowing serializable subclass

public abstract class AbstractFoo {

private int x, y; // Our state

// This enum and field are used to track initialization

private enum State { NEW, INITIALIZING, INITIALIZED };

private final AtomicReference<State> init = new AtomicReference<State>(State.NEW);

public AbstractFoo(int x, int y) { initialize(x, y); }

// This constructor and the following method allow

// subclass's readObject method to initialize our state.

protected AbstractFoo() { }

protected final void initialize(int x, int y) {

if (!init.compareAndSet(State.NEW, State.INITIALIZING))

throw new IllegalStateException("Already initialized");

this.x = x;

this.y = y;

... // Do anything else the original constructor did

init.set(State.INITIALIZED);

}

// These methods provide access to internal state so it can

// be manually serialized by subclass's writeObject method.

protected final int getX() { checkInit(); return x; }

protected final int getY() { checkInit(); return y; }

// Must call from all public and protected instance methods

private void checkInit() {

if (init.get() != State.INITIALIZED)

throw new IllegalStateException("Uninitialized");

}

... // Remainder omitted

}

// Serializable subclass of nonserializable stateful class

public class Foo extends AbstractFoo implements Serializable {

private void readObject(ObjectInputStream s)

throws IOException, ClassNotFoundException {

s.defaultReadObject();

// Manually deserialize and initialize superclass state

int x = s.readInt();

int y = s.readInt();

initialize(x, y);

}

private void writeObject(ObjectOutputStream s)

throws IOException {

s.defaultWriteObject();

// Manually serialize superclass state

s.writeInt(getX());

s.writeInt(getY());

}

// Constructor does not use the fancy mechanism

public Foo(int x, int y) { super(x, y); }

private static final long serialVersionUID = 1856835860954L;

}

Inner classes(Item 22) should not implement Serializable. A static member class can, however, implement Serializable.

Summary

Unless a class is to be thrown away after a short period of use, implementing Serializable is a serious commitment that should be made with care. Extra caution is warranted if a class is designed for inheritance. For such classes, an intermediate design point between implementing Serializable and prohibiting it in subclasses is to provide an accessible parameterless constructor. This design point permits, but does not require, subclasses to implement Serializable.

Effective Java 74 Implement Serializable judiciously的更多相关文章

  1. Effective Java 11 Override clone judiciously

    Principles If you override the clone method in a nonfinal class, you should return an object obtaine ...

  2. Effective Java 41 Use overloading judiciously

    The choice of which overloading to invoke is made at compile time. // Broken! - What does this progr ...

  3. Effective Java 42 Use varargs judiciously

    Implementation theory The varargs facility works by first creating an array whose size is the number ...

  4. Effective Java Index

    Hi guys, I am happy to tell you that I am moving to the open source world. And Java is the 1st langu ...

  5. 《Effective Java》读书笔记 - 11.序列化

    Chapter 11 Serialization Item 74: Implement Serializable judiciously 让一个类的实例可以被序列化不仅仅是在类的声明中加上" ...

  6. Effective Java 目录

    <Effective Java>目录摘抄. 我知道这看起来很糟糕.当下,自己缺少实际操作,只能暂时摘抄下目录.随着,实践的增多,慢慢填充更多的示例. Chapter 2 Creating ...

  7. 【Effective Java】阅读

    Java写了很多年,很惭愧,直到最近才读了这本经典之作<Effective Java>,按自己的理解总结下,有些可能还不够深刻 一.Creating and Destroying Obje ...

  8. EFFECTIVE JAVA 第十一章 系列化

    EFFECTIVE  JAVA  第十一章  系列化(将一个对象编码成一个字节流) 74.谨慎地实现Serializable接口 *实现Serializable接口付出的代价就是大大降低了“改变这个类 ...

  9. Effective Java通俗理解(下)

    Effective Java通俗理解(上) 第31条:用实例域代替序数 枚举类型有一个ordinal方法,它范围该常量的序数从0开始,不建议使用这个方法,因为这不能很好地对枚举进行维护,正确应该是利用 ...

随机推荐

  1. sitemesh学习笔记(1)

    最近在学习web开发的时候,发现很多的页面都存在同样的导航栏,登陆栏,js,jQuery等等相同的元素.这样就感觉开发变得好臃肿啊,并且,有时候改一个元素,就要把所有包含这个元素的页面全部重新码一遍, ...

  2. 为了去重复,写了一个通用的比较容器类,可以用在需要比较的地方,且支持Lamda表达式

    为了去重复,写了一个通用的比较容器类,可以用在需要比较的地方,且支持Lamda表达式,代码如下: public class DataComparer<T>:IEqualityCompare ...

  3. Spring基础——在 Spring Config 文件中基于 XML 的 Bean 的自动装配

    一.Spring IOC 容器支持自动装配 Bean,所谓自动装配是指,不需要通过 <property> 或 <constructor-arg> 为 Bean 的属性注入值的过 ...

  4. ActiveReports 报表应用教程 (3)---图表报表

    ActiveReports 的图表控件支持绝大多数常用的二维和三维图表类型,包括XY图表和财务图表.通过使用图表控件的定制功能,如修改坐标轴.图注.图例等,用户可以创建任何其所需要的图表效果.用户还可 ...

  5. 容器---List和AbstractList

    一.前言 前面我们介绍了Collection及其抽象实现,在JAVA的容器体系里,由Collection派生出来的有两大体系,即List和Map.本文以及后续文章将重点分析List体系.本文将重点分析 ...

  6. C语言范例学习03-下

    树与图 3.5 二叉树及其应用 PS:二叉树是最经典的树形结构,适合计算机处理,具有存储方便和操作灵活等特点,而且任何树都可以转换成二叉树. 实例101 二叉树的递归创建 实例102 二叉树的遍历 问 ...

  7. Follow me to learn how to use mvc template

    Introduction After having gone through many project: Project A Project B Project C I start to write ...

  8. 我所了解的WEB开发(4) - 神奇的URL

    如果说WEB开发中什么最为神奇的话,我觉得这当属URL了.         URL的启蒙应该是当年的互联网冲浪(surf the Internet),记得当年的电视上宣传互联网冲浪就好似今天对大数据的 ...

  9. C#获取网上图片的宽高代码

    用Visual Studio建立Console应用程序,记得引用程序集System.Drawing; 代码如下: using System;using System.Drawing;using Sys ...

  10. margin和padding对行内元素的影响

    这个是在面试的时候,面试官问我的一个小问题 自己没有考虑过inline元素设置margin和padding的问题 学习的过程记录下来 1)inline元素的高度是由元素的内容决定的(字体的大小和行高) ...