首页 > 解决方案 > 将 Protobuf 转换为 Java

问题描述

我知道可以将 protobuf 消息转换为 Java 类。我想知道是否可以在不编写翻译函数的情况下将 protobuf 消息转换为 Java 对象?

标签: javaprotocol-buffers

解决方案


是的,这是可能的。使用 protobuf 转换器。检查:https ://github.com/BAData 。

将域对象转换为 Protobuf:

ProtoObject protoObject =
    Converter.create().toProtobuf(ProtoObject.class, domainObject);

将 Protobuf 对象转换为域对象:

DomainObject domainObject = Converter.create().toDomain(DomainObject.class, protoObject)

您的域类需要使用@ProtoClass 进行注释,指定您希望域类映射到的原型类。例子:

@ProtoClass(ProtoObject.class)
Class DomainClass{
  @ProtoField
  private String field1;
  @ProtoField(name = "xyz") // in case proto and domain class field have different names
  private String field2;
}

我一直在使用它,它非常易于使用并且节省了很多精力。


推荐阅读