javaprotocol-buffers

Protobuf - builder doesn't exists?


I'm using the protobuf example ( for C# and java) :

The proto file

package tutorial;

option java_package = "com.example.tutorial";
option java_outer_classname = "AddressBookProtos";

message Person {
  required string name = 1;
  required int32 id = 2;
  optional string email = 3;

  enum PhoneType {
    MOBILE = 0;
    HOME = 1;
    WORK = 2;
  }

  message PhoneNumber {
    required string number = 1;
    optional PhoneType type = 2 [default = HOME];
  }

  repeated PhoneNumber phone = 4;
}

message AddressBook {
  repeated Person person = 1;
}

I already have a Person object :

Person john = Person
            .newBuilder()
            .setId(1234)
            .setName("John Doe")
            .setEmail("jdoe@example.com")
            .addPhone(
                    Person.PhoneNumber.newBuilder().setNumber("555-4321")
                            .setType(Person.PhoneType.HOME)).build();

Now let's suppose Ive read that object from a stream( working fine) , and now I want to update the Email :

The example here says to :

enter image description here

So I tried to get the email builder but I only see this :

enter image description here

Question

How can I edit this person of myne , and why does the exact code , doesn't work ?


Solution

  • The email is not defined as a sub message in your proto file, is a String.

    Protoc generates the messages as java classes, each generated class has a Builder sub class who extends com.google.protobuf.GeneratedMessage.Builder and implements all necesary methods to work and the builder is accesible via the appropiate getter.

    That's the reason why you cant get the PhoneNumber builder

    john.toBuilder().getPhoneBuilder(index);
    

    and set the PhoneNumber fields, because is defined as a sub message and has his own Builder

      message PhoneNumber {
        required string number = 1;
        optional PhoneType type = 2 [default = HOME];
      }
    

    and you can not get the email Builder, because the email does not exists as message sub class (with his own builder), is defined as a String and the builder is the Person Class builder

    optional string email = 3;
    

    If you want to change the email you can do

    john.toBuilder().setEmail("jdoe@example.com").buid();
    

    It is a bit confused but hope this helps.