Build an object from an existing one using lombok

前端 未结 2 1944
暖寄归人
暖寄归人 2020-12-03 02:36

Lets say I have a lombok annotated class like

@Builder
class Band {
   String name;
   String type;
}

I know I can do:

Band         


        
2条回答
  •  不思量自难忘°
    2020-12-03 02:57

    You can use the toBuilder parameter to give your instances a toBuilder() method.

    @Builder(toBuilder=true)
    class Foo {
       int x;
       ...
    }
    
    Foo f0 = Foo.builder().build();
    Foo f1 = f0.toBuilder().x(42).build();
    

    From the documentation:

    If using @Builder to generate builders to produce instances of your own class (this is always the case unless adding @Builder to a method that doesn't return your own type), you can use @Builder(toBuilder = true) to also generate an instance method in your class called toBuilder(); it creates a new builder that starts out with all the values of this instance.

    Disclaimer: I am a lombok developer.

提交回复
热议问题