Importing “google/protobuf/descriptor.proto” in ja

2019-02-13 18:28发布

问题:

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