首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Protobuf []到ProtoBuf编译类的转换

Protobuf []到ProtoBuf编译类的转换
EN

Stack Overflow用户
提问于 2022-02-09 07:16:41
回答 1查看 712关注 0票数 0

我正在处理以protobuf字节[]的形式接收传入的消息,我的方法是在继续将其转换为JSON格式之前,将其转换为protobuf编译的类。

下面是我目前拥有的代码片段,如果有人能就我应该纠正的领域向我提供建议,我将不胜感激。

代码语言:javascript
复制
public void conversionMethod(byte[] inputMessage) {
     
    try {
    
    byte[] wrapperMessage = inputMessage;
    
    Any any = Any.parseFrom(wrapperMessage);
    
    
    if (any.is(Teacher.class))
    {
      TeacherProto teacherProto = any.unpack(TeacherProto.class);
     
    } 
    
    
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    
}

我现在正在遵循这个链接中的指南,https://developers.google.com/protocol-buffers/docs/reference/java/com/google/protobuf/Any作为参考。

目前,我已经看到了这个错误。

代码语言:javascript
复制
The method is(Class<T>) in the type Any is not applicable
for the arguments (Class<ElevatorProto>)

我能做什么来解决这个问题?

EN

回答 1

Stack Overflow用户

发布于 2022-02-20 04:14:51

我不认为你想做的事是实际的。

首先,protobuf消息只包含字段号、线路类型和编码值。只有6种导线类型:

  • 0 Varint int32,int64,uint32,uint64,sint32,sint64,bool,enum
  • 1 64位fixed64,sfixed64,双倍
  • 2长度分隔的字符串、字节、嵌入消息、打包的重复字段
  • 3个起始组组(不推荐)
  • 4端组组(不推荐)
  • 5 32位

这不足以重构Java类的字段名和类型。

我不认为使用Any也是行不通的。根据Any实际上并不包含打包值类型的描述符。相反,它包含..。

..。作为消息类型的全局唯一标识符并解析的URL。

但是,AFAIK那个URL只是作为接收方已经知道的原型类型的标识符使用。它不包含构造(实际)消息所需的信息.以生成Java类。

更新--这可能帮不了你,但是根据Google "Any.proto“定义中的注释,可能实现类型解析器是可能的。

代码语言:javascript
复制
  // In practice, teams usually precompile into the binary all types that they
  // expect it to use in the context of Any. However, for URLs which use the
  // scheme `http`, `https`, or no scheme, one can optionally set up a type
  // server that maps type URLs to message definitions as follows:
  //
  // * If no scheme is provided, `https` is assumed.
  // * An HTTP GET on the URL must yield a [google.protobuf.Type][]
  //   value in binary format, or produce an error.
  // * Applications are allowed to cache lookup results based on the
  //   URL, or have them precompiled into a binary to avoid any
  //   lookup. Therefore, binary compatibility needs to be preserved
  //   on changes to types. (Use versioned type names to manage
  //   breaking changes.)
  //
  // Note: this functionality is not currently available in the official
  // protobuf release, and it is not used for type URLs beginning with
  // type.googleapis.com.

所以..。您可以设置自己的类型服务器来发布消息类型的定义。您可以(我猜)使用这些定义来生成protobuf类,也可以以更动态的方式生成JSON。

但以上所述至少意味着您的“组织”的某些部分了解并发布了这些类型。那么,为什么不直接获取所有已发布的类型,并使用它们在每次重新构建应用程序时生成相应的protobuf类?或者,为什么不维护protobuf类的库--发布这些类型的组的责任?

(好的。我明白为什么你希望你的应用程序比那些想法更有活力。但它值得付出额外的努力和复杂性吗?)

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71045367

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档