gpt4 book ai didi

java - 序列化代理

转载 作者:行者123 更新时间:2023-12-01 11:58:21 24 4
gpt4 key购买 nike

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

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

对于链表,这意味着我们不应该序列化任何实现细节,例如节点关系,而实际上只是“元素列表”。

我有链表实现,并且想在其中实现序列化代理模式(Effective Java(第2版),第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.

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

注意:List接口(interface)和LinkedList类是我自己的实现,而不是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?

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

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

很难理解为什么你必须发布这个问题,因为你已经有了受人尊敬的引用,并且你已经实现了答案,这反过来表明你已经理解了你所读到的内容。

关于java - 序列化代理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28182857/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com