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

时间:2014-01-12 15:00:27

标签: java serialization 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注册接口以进行序列化吗?

由于

1 个答案:

答案 0 :(得分:0)

使用addDefaultSerializer方法:

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