Custom Serializers
This page covers how to implement custom serializers for your types.
Basic Custom Serializer
In some cases, you may want to implement a serializer for your type, especially for classes that customize serialization using JDK writeObject/writeReplace/readObject/readResolve, which is very inefficient.
For example, if you don't want the following Foo#writeObject to be invoked, you can implement a custom serializer:
class Foo {
public long f1;
private void writeObject(ObjectOutputStream s) throws IOException {
System.out.println(f1);
s.defaultWriteObject();
}
}
class FooSerializer extends Serializer<Foo> {
public FooSerializer(Fory fory) {
super(fory, Foo.class);
}
@Override
public void write(MemoryBuffer buffer, Foo value) {
buffer.writeInt64(value.f1);
}
@Override
public Foo read(MemoryBuffer buffer) {
Foo foo = new Foo();
foo.f1 = buffer.readInt64();
return foo;
}
}
Register the Serializer
Fory fory = getFory();
fory.registerSerializer(Foo.class, new FooSerializer(fory));
Besides registering serializers, you can also implement java.io.Externalizable for a class to customize serialization logic. Such types will be serialized by Fory's ExternalizableSerializer.
Collection Serializer
When implementing a serializer for a custom Collection type, you must extend CollectionSerializer or CollectionLikeSerializer. The key difference is that CollectionLikeSerializer can serialize a class which has a collection-like structure but is not a Java Collection subtype.