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 import google/protobuf/any.proto.
Any message類型允許我們在沒有.proto定義的情況下,作為內(nèi)嵌類型使用message類型。一個Any類型包含了一個任意序列化的消息作為bytes(字節(jié)),以及一個URL代表著該message類型的全局唯一標(biāo)識符,并解析為該message的類型。為了使用Any類型,你需要導(dǎo)入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類型的默認(rèn)值類型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:
不同的語言實(shí)現(xiàn)將支持運(yùn)行時庫來幫助以類型安全的方式打包或解包Any數(shù)據(jù) - 舉個例子,在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 ...
}
}