Generic Parsing of PB in java

Is it possible to parse PB in a generic fashion in java ? I looked into GeneratedMessage and could not find a way to parse any PB byte buffer into a GeneratedMessage. Essentially, i am trying to parse a PB byte buffer into GeneratedMessage and then i would use reflection to detect fields inside it.Thanks in advance


First of all, you can't parse PB data without knowing the schema. The schema originally comes from a ".proto" file and is typically embedded in the code generated byprotoc. However, you can also tell protoc to store the schema in a format that's usable by the Java Protobuf library:

protoc --descriptor_set_out=mymessages.desc mymessages.proto

Then load it in your Java code:

FileInputStream fin = new FileInputStream("mymessages.desc");
Descriptors.FileDescriptorSet set =
  Descriptors.FileDescriptorSet.parseFrom(fin);
Descriptors.Descriptor md = set.getFile(0).getMessageType(0);

Once you have the schema for a message (Descriptor.Descriptor) parsing a message is easy:

byte[] data = ...;
DynamicMessage m = DynamicMessage.parseFrom(md, data);

ynamicMessage has a reflective API that lets you look through the fields.

The messy part is calling out to the protoc tool to convert the ".proto" file into a usable format. The C++ Protobuf library has a way to load ".proto" files directly, but unfortunately the Java Protobuf library does not.




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值