Mayday
Mayday

Reputation: 5146

How to import internal protobuf messages?

I have read that in proto3, they have removed the ability to know if a field is set or not. As a solution, I have read in several sites, you can embed your primitives into a wrapper message.

As you can see here, protobuf has some internal packages under wrappers.proto in order to do exactly what I need.

I could copy and paste that wrappers.proto file into my system, and import it from another file A.proto to use them.

However I wonder:

  1. Would it be a good choice to use their internal wrappers?

  2. If so, could I import directly from their jar instead of creating my own copy of the file?

(I tried to import using their jar directory, but did not work)

import "lib/protobuf-java-3.5.0.jar/com/protobuf/wrappers.proto"; --> fails

while:

import "resources/protoBeans/wrappers.proto"; --> my own copy --> works

Upvotes: 2

Views: 4826

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1064114

You can, and it would probably be preferable to creating them separately - although note that sub-messages add some overhead to the binary size and processing and aren't wire-compatible with a proto2 message that used an optional field to achieve the same thing. The "wrappers.proto" should already be available underneath protoc's binary location; a typical usage might be:

syntax = "proto3";
import "google/protobuf/wrappers.proto";

message Foo {
    .google.protobuf.Int32Value foo = 1;
}

An additional advantage of using "wrappers.proto" rather than re-implementing it yourself is that it will count as a "well-known type" with bespoke JSON handling and better "any" support.

Upvotes: 4

Related Questions