Java Serialization with Protocol Buffer

感情迁移 提交于 2019-12-05 08:12:15
Aravind R. Yarram

Perspective 1

You write a .proto file and give it to protoc that generates the Builder code. They are suggesting not to add any methods to the generated code. If at all you want some custom behavior to be added to the generated code then WRITE YOUR OWN CLASS WRAPPING the generated code.

For e.g let us say the protoc generated class is MyMessageBuilder. And you wanted to add a method that can take XML input and spitout the protobuff specific message out. You would write a XmlToMyMessageBuilder as below. Here XmlToMyMessageBuilder, your class is wrapping the generated code and adding custom behavior fromXml().

public class XmlToMyMessageBuilder
{
    private final MyMessageBuilder protoBuilder;

    public MyMessage fromXml(byte[] input()
    {
        protoBuilder.setXXX();
    }
}

This is a general good programming principle.

Perspective 2

By providing a intermediary you can also DECOUPLE your code from the underlying serialization mechanism. This allows you to switch the serializer implementations (say you want to serialize a payload where all the data is in string format...where JSON seriazation with compression is a better alternative) with low impact. You could do something like this

public interface MySerializer
{
    boolean serialize(MyDomainObject input);
}

public PBBasedSerializer implements MySerializer
{
    private final MyMessageBuilder protoBuilder;
    ...
}

public JsonBasedSerializer implements MySerializer
{
    private final JSONSerializer jsonSerializer;
    ...
}

It means that you would implement your own class that contains a protocol buffer object as a private field.

Protocol buffer classes are generated from .proto files. These generated classes have all methods to directly manipulate the fields they contain. But they don't have methods that serve higher level operations than just modifying a field.

Your wrapper class can then provide a richer or more restricted interface to users of your API. As any modification of the protocol buffer needs to go through the wrapping object, you have full control about what operations you want to support.

禪 師 無

What does it mean when it says to wrap the created class?

They're handing you a class, wrap it with a child class purpose built for what you're doing. Don't interact with a raw class instance from the library.

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