如何使用接口对 Kryo 对象进行序列化/反序列化



是否可以通过注册接口而不是 concreate 类来使用 Kryo 序列化/反序列化对象?

在 concreate 中,我需要序列化一个 Java 7 Path 对象,该对象定义为在接口中。

我尝试编写一个序列化程序,将路径 URI 保存为字符串并在读取反序列化期间重新创建它。但事实证明,我的序列化编写器方法从未被 Kryo 调用。

这是我的(Groovy)代码:

class PathSerializer extends FieldSerializer<Path> {
    PathSerializer(Kryo kryo) {
        super(kryo, Path)
    }
    public void write (Kryo kryo, Output output, Path path) {
        def uri = path.toUri().toString()
        kryo.writeObject(output, uri)
    }
    public Path read (Kryo kryo, Input input, Class<Path> type) {
        def uri = kryo.readObject(input,String)
        Paths.get(new URI(uri))
    }
}
def kryo = new Kryo()
kryo.register(Path, new PathSerializer(kryo))
def path = Paths.get('hola')
Output output = new Output(new FileOutputStream("file.bin"));
kryo.writeObject(output, path);
output.close();

知道如何使用 Kryo 注册用于序列化的接口吗?

谢谢

使用 addDefaultSerializer 方法:

kryo.addDefaultSerializer(Path, new PathSerializer(kryo))

最新更新