Java中的泛型Parsing [英] Generic Parsing of PB in java
问题描述
是否可以在Java中以通用方式解析protobuf?
Is it possible to parse protobuf in a generic fashion in Java?
我查看了GeneratedMessage,找不到将任何PB字节缓冲区解析为GeneratedMessage的方法。
I have looked into GeneratedMessage and could not find a way to parse any PB byte buffer into a GeneratedMessage.
基本上,我试图将PB字节缓冲区解析为GeneratedMessage,然后我会使用反射来检测其中的字段。
Essentially, I am trying to parse a PB byte buffer into GeneratedMessage and then I would use reflection to detect fields inside it.
推荐答案
首先,在不知道架构的情况下,无法解析PB数据。模式最初来自.proto文件,通常嵌入在 protoc
生成的代码中。但是,您也可以告诉 protoc
以Java Protobuf库可用的格式存储架构:
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 by protoc
. 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
然后将它加载到Java代码中:
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);
获得消息的架构后( Descriptor.Descriptor
)解析消息很简单:
Once you have the schema for a message (Descriptor.Descriptor
) parsing a message is easy:
byte[] data = ...;
DynamicMessage m = DynamicMessage.parseFrom(md, data);
DynamicMessage
有一个反光的API可以让你浏览字段。
DynamicMessage
has a reflective API that lets you look through the fields.
凌乱的部分是调用 protoc
工具来转换.proto将文件转换为可用格式。 C ++ Protobuf库有一种直接加载.proto文件的方法,但不幸的是Java Protobuf库没有。
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.
这篇关于Java中的泛型Parsing的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!