Reputation: 2720
I'm trying to use extensions with Google's Protocol Buffers. I've got one "main" proto file and several other proto files that "extend" the main one.
In my java code, I'm not 100% sure how to add to a repeating message correctly. When I run the java code I've written, the toString() method shows that the extension attributes added, but it doesn't decode properly (probably because I ran a build() call on the added Collar object).
How should I properly add repeating elements to extended items in a proto file?
File1.proto
package protocol_buffer;
option java_outer_classname = "PetClass";
message Pet {
optional string pet_name = 1;
extensions 100 to 199;
}
File2.proto
import "File1.proto";
option java_outer_classname = "CollarClass";
message Collars {
optional string collar_type = 1;
optional string collar_color = 2;
}
extend pet {
repeated Collars collar = 100;
}
MyFile.java
Pet pet = Pet.newBuilder()
.setPetName("Fido")
.addExtension(CollarClass.collar,
Collar.newBuilder()
.setCollarType("round")
.setCollarColor("brown")
.build()
)
.build();
System.out.println(pet.toString());
Upvotes: 1
Views: 4908
Reputation: 2720
I figured out my problem. I was correctly adding the extension to "Pet". When parsing a protobuf byte array, you need to add an extension registry so that the function knows what extensions to parse.
ExtensionRegistry registry = ExtensionRegistry.newInstance();
registry.add(CollarClass.collar);
Pet pet = Pet.parseFrom(new FileInputStream(<some file>),registry);
Upvotes: 2