Build an object from an existing one using lombok

前端 未结 2 1952
暖寄归人
暖寄归人 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:51

    Is there an easy way to create an object of Foo using the existing object as a template and changing one of it's properties? (emphasis mine)

    If you really want to change a single property, then there's a nicer and more efficient way:

    @With
    class Band {
       String name;
       String type;
    }
    
    Band nirvana = rollingStones.withName("Nirvana");
    

    The wither creates no garbage, but it can change just a single field. For changing many fields, you could use

    withA(a).withB(b).withC(c)....
    

    and produce tons of garbage (all intermediate results) but than toBuilder is more efficient and more natural.

    NOTE: Older versions of lombok have used @Wither annotation. See beginning of documentation.

提交回复
热议问题