protocol-buffers - proto3 中的扩展

标签 protocol-buffers

给定以下原型(prototype)定义:

syntax = "proto3";

import "google/protobuf/descriptor.proto";

option java_package = "com.example.dto";

option java_multiple_files = true;

extend google.protobuf.FieldOptions {
    Projector projector = 50002;
}

message Projector {
    string name = 1;
    string class = 2;
    bool default = 3;
}

message SearchRequest {
    string query = 1 [(projector) = {name: "queryProjector", class: "foobar"}];
    int32 page_number = 2;
    int32 result_per_page = 3;
}

如何访问字段扩展?

据我所知,扩展在 proto3 中仍然有效,但通常被 Any 类型取代?

我是这么远的:

final Descriptors.Descriptor descriptor = SearchRequest.getDescriptor();

final Descriptors.FieldDescriptor query = descriptor.findFieldByName("query");

这是正确的方法吗?下一步是什么?

最佳答案

如此处所述https://github.com/google/protobuf/issues/1460

Custom options are still supported. It's the only place where you can use extensions in proto3. It works the same way as in proto2. Languages that don't support proto2 may provide a special API to access custom options as they don't support extensions.

所以自定义选项似乎仍然受支持,你应该使用它们

descriptor.findFieldByName("query").getOptions().getAllFields();

这将返回您自定义选项的 map (作为字段)

final Map<Descriptors.FieldDescriptor, Object> allFields;

而该值将是您的选项类型,在您的情况下为投影仪。

此自定义选项(投影仪)的 FileDescriptor 似乎是在使用驼峰式命名的 *.proto 文件命名的类中作为公共(public)静态生成的。

如果您的原型(prototype)文件名为 search_service_v1.proto,您可能会直接找到自定义选项,如下所示:

final DescriptorProtos.FieldOptions options descriptor.findFieldByName("query").getOptions();
final Object field = options.getField(SearchServiceV1.projector.getDescriptor());

你会在

final Projector projector = Projector.class.cast(field);

关于protocol-buffers - proto3 中的扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46619005/

相关文章:

java - 领导者选举 LCR

visual-studio-code - VS Code PyLint 错误 E0602( undefined variable )与 ProtoBuf 编译的 Python 结构

go - 无法制作grpc-gateway .gw.pb,并且没有错误

java - 解决由于 C++ 导致的 Google protobuf 中枚举字段命名限制的解决方案

c# - Protobuf 解码任意消息。 Protobuf 消息多态性

java - 来自 Java List<List<Object>> 的 Protobuf 消息

c# - 对 C# 和 C++ 项目使用相同的 .proto 文件

java - 在没有源文件的情况下反序列化 protobuf

ios - 在 iOS 中本地存储 protobuf 对象

时间:2019-03-17 标签:c#protobufreflectionus