Home > OS >  Deep copy with lombok toBuilder within a nested class - cleaner way?
Deep copy with lombok toBuilder within a nested class - cleaner way?

Time:01-20

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder(toBuilder = true)
public class Example {
  public ExampleTwo exampleTwo;

@lombok.Data
@AllArgsConstructor
@NoArgsConstructor
@Builder(toBuilder = true)
public static class ExampleTwo {
    private SomeData someData;
    private AnotherField anotherField;

   }

}

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder(toBuilder = true)
public class SomeData {
   private String specialId;
   private String firstName;
   private String lastName;

}

So I retrieved an Example instance and made a deep copy to duplicate it. But I want to be able to set one of the fields of the copied object which is specialId from the SomeData nested class. My current working implementation is this:

     SomeData someData = example.getExampleTwo().getSomeData().toBuilder().specialID("SPE_1").build();
     Example.ExampleTwo exampleTwo = example.getExampleTwo().toBuilder().someData(someData).build();
     Example duplicateExample = example.toBuilder().exampleTwo(exampleTwo).build();

Do you have thoughts on ways to make this cleaner without having to go through these additional steps? Would prefer it to be easier to read. I'm avoiding Serializable implementation and declaring it as a Cloneable interface since I've read to avoid those. Last resort would be to use a library.

CodePudding user response:

@With might be helpful:

Example example = Example.builder().build();
Example.ExampleTwo exampleTwo = example.getExampleTwo();
SomeData someData = exampleTwo.getSomeData();

return example.withExampleTwo(
        exampleTwo.withSomeData(
                someData.withSpecialId("SPE_1")
        )
);
  • Related