Importing “google/protobuf/descriptor.proto” in java protocol buffers

陌路散爱 提交于 2019-11-29 20:08:59

问题


I have a .proto file definition which needs to import "google/protobuf/descriptor.proto" because I use Custom Options.

So in my .proto file I do:

import "google/protobuf/descriptor.proto";
package ...;

...

Since my file didn't compile complaining about the dependency, I got a copy of the descriptor.proto file placing it in the same directory my proto file was.

This solved the problem but I don't believe this is the correct way. Now the descriptor.proto gets compiled together with my .proto file resulting in having 2 compiled descriptor.proto at runtime:

  • the one shipped with the protobuf-java-2.5.0.jar file
  • the one which was compiled together with my .proto file

I think the --proto-path option should be used somehow but not entirely sure what is the correct way.

Thanks for the best practise tip here!


回答1:


When I have used descriptor in a .proto, I have used it like

import "google/protobuf/descriptor.proto";

message AddressBook {
  required google.protobuf.FileDescriptorSet proto_files = 1;

Then to generate the java (on windows) with addressbookSD.proto in the default directory:

protoc addressbookSD.proto --java_out=./ --proto_path=./ --proto_path=<protobuf-install-directory>\src

where <protobuf-install-directory> is the protocol buffers install directory. The key point is descriptor.proto is in

<protobuf-install-directory>\src\google\protobuf

The levels in an protobuf import stament must match directories in the File system just like they would in java.

So I use <protobuf-install-directory>\src as the import directory, The directory structure must be

<protobuf-install-directory>\src
    +-- google
         +-- protobuf
             +-- descriptor.proto


来源:https://stackoverflow.com/questions/20069295/importing-google-protobuf-descriptor-proto-in-java-protocol-buffers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!