Proto3:Any
The Any message type lets you use messages as embedded types without having their .proto definition. An Anycontains an arbitrary serialized message as bytes, along with a URL that acts as a globally unique identifier for and resolves to that message's type. To use the Any type, you need to importgoogle/protobuf/any.proto.Any message类型允许我们在没有.proto定义的情况下,作为内嵌类型使用message类型。一个Any类型包含了一个任意序列化的消息作为bytes(字节),以及一个URL代表着该message类型的全局唯一标识符,并解析为该message的类型。为了使用Any类型,你需要导入google/protobuf/any.proto。
import "google/protobuf/any.proto";message ErrorStatus {string message = 1;repeated google.protobuf.Any details = 2;}
The default type URL for a given message type is type.googleapis.com/_packagename_._messagename_.
给定message类型的默认值类型URL是type.googleapis.com/_packagename_._messagename_。
Different language implementations will support runtime library helpers to pack and unpack Any values in a typesafe manner – for example, in Java, the Any type will have special pack() and unpack() accessors, while in C++ there are PackFrom() and UnpackTo() methods:
不同的语言实现将支持运行时库来帮助以类型安全的方式打包或解包Any数据 - 举个例子,在Java中,Any类型会有特殊的pack()和unpack()访问器,而C++提供了PackFrom()和UnpackTo()方法:
// Storing an arbitrary message type in Any.NetworkErrorDetails details = ...;ErrorStatus status;status.add_details()->PackFrom(details);// Reading an arbitrary message from Any.ErrorStatus status = ...;for (const google::protobuf::Any& detail : status.details()) {if (detail.Is<NetworkErrorDetails>()) { NetworkErrorDetails network_error; detail.UnpackTo(&network_error); ... processing network_error ...}}
页:
[1]