Making a small change to a Java protocol buffers o

2020-05-24 21:04发布

问题:

I want to make a small change, deep in tree of Java protocol buffer objects.

I can use the .getBuilder() method to make a new object that is a clone of an old one with some changes.

When this is done at a deep level, the code becomes ugly:

Quux.Builder quuxBuilder = foo.getBar().getBaz().getQuux().toBuilder()
Baz.Builder bazBuilder = foo.getBar().getBaz().toBuilder()
Bar.Builder barBuilder = foo.getBar().toBuilder()
Foo.Builder fooBuilder = foo.toBuilder()

quuxBuilder.setNewThing(newThing);
bazBuilder.setQuux(quuxBuilder);
barBuilder.setBaz(bazBuilder);
fooBuilder.setBar(barBuilder);

Foo newFoo = fooBuilder.build();

(This is just 4 levels, I'm routinely dealing with 5-8 levels.)

Is there a better way?

回答1:

Another option is (I think; it's been a while):

Foo.Builder fooBuilder = foo.toBuilder();
fooBuilder.getBarBuilder().getBazBuilder().getQuuxBuilder()
    .setNewThing(newThing);
newFoo = fooBuilder.build();

Note that this isn't any more efficient; you're still making copies of foo, bar, baz, and quux.