Protobuf解析器解析其他对象?

Protobuf parser parses other objects?

我在 Java 的一个项目中一直在使用协议缓冲区。我发现 protobuf 对象的解析器解析其他 Protobuf 数据并且不会抛出异常。相反,它 returns 一个没有任何数据的解析器类型的对象(不是默认实例)

下面是我的测试原型文件

option java_package = "tester";
option java_outer_classname = "TestProto";

message A{
    string message = 1;
}

message B{
    int64 id = 1;
}

下面是我的测试代码

 TestProto.A a = TestProto.A.newBuilder().setMessage("My Test Message").build();
 TestProto.B b = TestProto.B.getDefaultInstance().getParserForType().parseFrom(a.toByteString());

 System.out.println("Is default instnace :" + (b.getDefaultInstanceForType() == b));

此代码无一例外地工作,结果是 'false'。

我无法理解这种行为,我需要一种情况,我必须解析一些序列化的 protobuf 对象,如果一个解析器失败,我必须尝试另一个解析器。我该如何解决这个问题。

谢谢。

Protobuf 的前提是两端事先知道并同意数据结构。如果您尝试用 完全不同的 结构来解释消息,则准确地说是零保证。

  • 它可能会引发错误
  • 它可以工作并向您呈现 well-intentioned 乱码
  • 它可以工作并将所有需要的内容保留为未知字段

一切皆有可能。

基本上:您不能依赖这种行为。

注意:某些 更改做出了保证,例如添加或删除字段(确保以后不会重复使用它们)不同 types/meanings)。这很好,也是意料之中的。但其他变化根本就没有定义。


I am in need of a situation where I have to parse some serialized protobuf objects and If one parser fails I have to try the other parser. How can I solve this.

你不能。