本文讲述protocol buffer编译器会由协议定义文件生成什么样的代码。proto2和proto3的区别将被高亮——注意,本文说的是存在于生成代码中的区别,不是基本的消息类/接口——它们在这两个版本中是一样的。在开始本文之前,你应该先看一下proto2的语言指南和proto3语言指南。
编译器调用
Protocol buffer 编译器在遇到 –java_out= 命令行标识时会产生Java输出。
–java_out=选项参数指定编译器的输出目录。编译器为每一个.proto文件创建一个.java文件。这个文件包含一个java外部类,其中定义了一些基于.proto文件中声明的内部类和一些静态字段。
外部类的名产生规则:如果.proto文件包含了如下的一行:
option java_outer_classname = "Foo";
外部类的名字将会是 Foo。否则,外部类的名字会变成由.proto文件名转换而成的驼峰形式。例如,foo_bar.proto将会变成FooBar。如果该文件中已经有一个消息有同样的名字,“OuterClass”将会被追加到外部类的名字后边。例如,如果foo_bar.proto包含一个叫FooBar的消息,外部类会变成FooBarOuterClass。
Java的包名会由下边的Package来决定。
输出什么样的文件完全由–java_out选项,包名 ( .s 被替换成 /s),和.java文件名来决定。
举个例子,你可以像下边这样调用编译器:
protoc --proto_path=src --java_out=build/gen src/foo.proto
如果foo.proto的java包是com.example,它的外部类名是FooProtos,那么protocol buffer编译器会生成文件:build/gen/com/example/FooProtos.java。Protocol buffer编译器将会自动创建build/gen/com/example目录,如果需要的话。但是,它不会创建build/gen或者build目录;它们必须已经存在。你可以在单个命令调用中指定多个.proto文件;所有输出文件会一次生成。
protoc的使用:
$ protoc.exe -h
Usage: D:\DEV\grpc\protoc-3.0.0-win32\bin\protoc.exe [OPTION] PROTO_FILES
Parse PROTO_FILES and generate output based on the options given:
-IPATH, --proto_path=PATH Specify the directory in which to search for
imports. May be specified multiple times;
directories will be searched in order. If not
given, the current working directory is used.
--version Show version info and exit.
-h, --help Show this text and exit.
--encode=MESSAGE_TYPE Read a text-format message of the given type
from standard input and write it in binary
to standard output. The message type must
be defined in PROTO_FILES or their imports.
--decode=MESSAGE_TYPE Read a binary message of the given type from
standard input and write it in text format
to standard output. The message type must
be defined in PROTO_FILES or their imports.
--decode_raw Read an arbitrary protocol message from
standard input and write the raw tag/value
pairs in text format to standard output. No
PROTO_FILES should be given when using this
flag.
-oFILE, Writes a FileDescriptorSet (a protocol buffer,
--descriptor_set_out=FILE defined in descriptor.proto) containing all of
the input files to FILE.
--include_imports When using --descriptor_set_out, also include
all dependencies of the input files in the
set, so that the set is self-contained.
--include_source_info When using --descriptor_set_out, do not strip
SourceCodeInfo from the FileDescriptorProto.
This results in vastly larger descriptors that
include information about the original
location of each decl in the source file as
well as surrounding comments.
--dependency_out=FILE Write a dependency output file in the format
expected by make. This writes the transitive
set