如何接收序列化事件?你可以在java序列化中定义Kryo中的序列化事件
void writeObject(ObjectOutputStream out) {
// handle event
out.defaultWriteObject(this);
}
并且当你的对象被序列化时这个方法会被调用。你怎么在Kryo做同样的事情? KryoSerializable
和Externalizable
都有默认序列化的问题:一旦你调用你的事件处理程序,就需要默认的读/写对象。但是没有这样的事情! ?您可以调用 read(Kryo, Input)
来读取对象的字段,但它会生成一个新对象,而不是填充当前对象。出于这个原因,我想介绍一个自定义序列:
Serializer def = kryo.getDefaultSerializer(A.class)
kryo.addDefaultSerializer(A.class, new Serializer() {
public void write(Kryo kryo, Output output, Object object) {
((A)object).serializationEvent();
def.write(kryo, output, object);
但是,我提到过一个子类接收serializationEvent()
事件,只有的A.class领域序列化。所以,这对class B extends A
不起作用。我也试过解决方案proposed by Natan:register(A.class, new FieldSerializer(A.class, myhandler
。这将序列化所有字段,包括子类,但是,自定义序列化程序根本不会为子类调用。所以,我决定Kryo定制只适用于最终课程。 Nathan says that this conclusion is "invalid" and KryoSerializable solution "application-specific" and thinking otherwise "rude".尽管有这样的解决方案,我决定发布我发现的一般方法。