pinakin
pinakin

Reputation: 442

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 ?

Upvotes: 4

Views: 5767

Answers (1)

user2900180
user2900180

Reputation:

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();

Upvotes: 6

Related Questions