Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java copy one protobuff object to other protobuff object

I've two protobuff object Source and Target for example

message Source{
   optional string firstName = 1;
   optional string lastName = 2;
}

message Target {
   optional string firstName = 1;
   optional string lastName = 2;
}

I want to copy fields from Source to Target, solution that I have

if(source.hasFirstName()) target.setFirstName(source.getFirstName());
if(source.hasLastName()) target.setLastName(source.getLastName());

Above code looks verbose. Is there simple solution available in Java 8 to handle this ?

like image 477
pinakin Avatar asked Oct 22 '25 15:10

pinakin


1 Answers

If your messages are identical, like in provided example, and only their names are different, you can serialize Source to an array and then deserialize it into target.

Target target = Target.parseFrom(source.toByteArray());

If field's names and types are identical, but has different numbers you can derialize/deserialize it as text

Target.Builder builder = Target.newBuilder();
TextFormat.merge(source.toString(), builder);
Target target = builder.build();

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!