序列化代理

Serialization proxy

我读到我们应该只序列化对象的逻辑部分。

Using the default serialized form when an object’s physical representation differs substantially from its logical data content has four disadvantages:

...//they relate to default serialization form and have no relation to subject

//and about linked list of Strings:

A reasonable serialized form for StringList is simply the number of strings in the list, followed by the strings themselves. This constitutes the logical data represented by a StringList, stripped of the details of its physical representation.

Effective Java (2nd Edition), Item 75

在链表的情况下,这意味着我们不应该序列化任何实现细节,如节点关系,但实际上只有 "list of elements"。

我有链表实现,想实现Serialization Proxy pattern(Effective Java (2nd Edition), Item 78) 在其中,但也不要违反上述规则。还有一句引述:

The serialization proxy pattern is reasonably straightforward. First, design a private static nested class of the serializable class that concisely represents the logical state of an instance of the enclosing class. This nested class, known as the serialization proxy, should have a single constructor, whose parameter type is the enclosing class. This constructor merely copies the data from its argument: it need not do any consistency checking or defensive copying. By design, the default serialized form of the serialization proxy is the perfect serialized form of the enclosing class.

那么在序列化代理中序列化对象的逻辑状态是唯一正确的吗class(正如我在下面所做的那样)或者例如列表的头节点的序列化是实现细节也是正确的吗?

注意:List接口和LinkedListclass是我自己实现的,不是java.util

//...
private static class SerializationProxy<E> implements Serializable {
        private final E[] elements;

        SerializationProxy(List<? extends E> list) {
            elements = list.toArray(Object.class); //returns array with all elements
        }

        private Object readResolve() {
            return new LinkedList<E>(elements); //constructor that take array and wraps it back in LinkedList
        }

        private static final long serialVersionUID = 123131234141423234L;
    }


    private void readObject(ObjectInputStream stream)
        throws InvalidObjectException {
    throw new InvalidObjectException("Proxy required");
    }

    private Object writeReplace() {
        return new SerializationProxy<E>(this); //pass enclosing class for proxy serializtion
    }
//...

如果这里有什么不清楚的地方full implementation. 提前致谢。

is it only right to serialize logical state of object in Serialization Proxy class(as i've done below)

你的语录就是这么说的。

or for example serialization of list's head node which is implementation details is right too?

这正是您的引文所警告的。

并不是说我一定同意引文。例如,我原则上不反对序列化链接。可能会有实际反对意见,例如递归深度,但那是另一回事。

很难理解为什么你必须 post 这个问题,当你已经有一个受人尊敬的引用,并且当你已经实施了答案,这反过来表明你已经理解了你所读的内容.