How serialise/de-serialise an object with Kryo by using an interface

断了今生、忘了曾经 提交于 2019-12-08 00:27:52

问题


Is it possible to serialise/de-serialise an object with Kryo by registering an interface instead of a concreate class?

In concreate I need to serialise a Java 7 Path object which is defined as in interface.

I tried writing a serialiser that saves the path URI as a string and recreates it during the read deserialisation. But it turns out the my serialise writer method is never invoked by Kryo.

This is my (Groovy) code:

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();

Any idea how to register an interface for serialization with Kryo?

Thanks


回答1:


Use the addDefaultSerializer method:

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


来源:https://stackoverflow.com/questions/21076136/how-serialise-de-serialise-an-object-with-kryo-by-using-an-interface

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!