我正在处理以protobuf字节[]的形式接收传入的消息,我的方法是在继续将其转换为JSON格式之前,将其转换为protobuf编译的类。
下面是我目前拥有的代码片段,如果有人能就我应该纠正的领域向我提供建议,我将不胜感激。
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作为参考。
目前,我已经看到了这个错误。
The method is(Class<T>) in the type Any is not applicable
for the arguments (Class<ElevatorProto>)我能做什么来解决这个问题?
发布于 2022-02-20 04:14:51
我不认为你想做的事是实际的。
首先,protobuf消息只包含字段号、线路类型和编码值。只有6种导线类型:
这不足以重构Java类的字段名和类型。
我不认为使用Any也是行不通的。根据这,Any实际上并不包含打包值类型的描述符。相反,它包含..。
..。作为消息类型的全局唯一标识符并解析的URL。
但是,AFAIK那个URL只是作为接收方已经知道的原型类型的标识符使用。它不包含构造(实际)消息所需的信息.以生成Java类。
更新--这可能帮不了你,但是根据Google "Any.proto“定义中的注释,可能实现类型解析器是可能的。
// 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类的库--发布这些类型的组的责任?
(好的。我明白为什么你希望你的应用程序比那些想法更有活力。但它值得付出额外的努力和复杂性吗?)
https://stackoverflow.com/questions/71045367
复制相似问题