拒做PB Boy!教你巧用 Protobuf 反射来优化代码( 二 )


message Student{  optional string name = 1;  optional string gender = 2;  optional string phone = 5;}其中字段phone,其index为 5,但是其number为 2 。
同时还有一个我们在调试中经常使用的函数:
std::string Descriptor::DebugString(); // 将message转化成人可以识别出的string信息2.2 类 FieldDescriptor 介绍类 FieldDescriptor 的作用主要是对 Message 中单个字段进行描述,包括字段名、字段属性、原始的 field 字段等 。
其获取获取自身信息的函数:
const std::string & name() const; // Name of this field within the message.const std::string & lowercase_name() const; // Same as name() except converted to lower-case.const std::string & camelcase_name() const; // Same as name() except converted to camel-case.CppType cpp_type() const; //C++ type of this field.其中cpp_type()函数是来获取该字段是什么类型的,在 PB 中,类型的类目如下:
enum FieldDescriptor::Type {  TYPE_DOUBLE = = 1,  TYPE_FLOAT = = 2,  TYPE_INT64 = = 3,  TYPE_UINT64 = = 4,  TYPE_INT32 = = 5,  TYPE_FIXED64 = = 6,  TYPE_FIXED32 = = 7,  TYPE_BOOL = = 8,  TYPE_STRING = = 9,  TYPE_GROUP = = 10,  TYPE_MESSAGE = = 11,  TYPE_BYTES = = 12,  TYPE_UINT32 = = 13,  TYPE_ENUM = = 14,  TYPE_SFIXED32 = = 15,  TYPE_SFIXED64 = = 16,  TYPE_SINT32 = = 17,  TYPE_SINT64 = = 18,  MAX_TYPE = = 18}类 FieldDescriptor 中还可以判断字段是否是必填,还是选填或者重复:
bool is_required() const; // 判断字段是否是必填bool is_optional() const; // 判断字段是否是选填bool is_repeated() const; // 判断字段是否是重复值类 FieldDescriptor 中还可以获取单个字段的index或者tag:
int number() const; // Declared tag number.int index() const; //Index of this field within the message's field array, or the file or extension scope's extensions array.类 FieldDescriptor 中还有一个支持扩展的函数,函数如下:
// Get the FieldOptions for this field.  This includes things listed in// square brackets after the field definition.  E.g., the field://   optional string text = 1 [ctype=CORD];// has the "ctype" option set.  Allowed options are defined by FieldOptions in// descriptor.proto, and any available extensions of that message.const FieldOptions & FieldDescriptor::options() const具体关于该函数的讲解在 2.4 章 。
2.3 类 Reflection 介绍该类提供了动态读、写 message 中单个字段能力 。
读单个字段的函数如下:
// 这里由于篇幅,省略了一部分代码,后面的代码部分也有省略,有需要的可以自行阅读源码 。int32 GetInt32(const Message & message, const FieldDescriptor * field) conststd::string GetString(const Message & message, const FieldDescriptor * field) constconst Message & GetMessage(const Message & message, const FieldDescriptor * field, MessageFactory * factory = nullptr) const // 读取单个message字段写单个字段的函数如下:
void SetInt32(Message * message, const FieldDescriptor * field, int32 value) constvoid SetString(Message * message, const FieldDescriptor * field, std::string value) const获取重复字段的函数如下:
int32 GetRepeatedInt32(const Message & message, const FieldDescriptor * field, int index) conststd::string GetRepeatedString(const Message & message, const FieldDescriptor * field, int index) constconst Message & GetRepeatedMessage(const Message & message, const FieldDescriptor * field, int index) const


推荐阅读