Immutable Lombok annotated class with Jackson

后端 未结 9 2134
再見小時候
再見小時候 2020-12-25 13:02

What is the preferred way to create class that is

  • Immutable
  • Can be serialized/deserialized with Jackson
  • Human-readable and with low level of
9条回答
  •  孤城傲影
    2020-12-25 13:41

    Another alternative that is much less verbose:

    @Data
    @Setter(AccessLevel.NONE)
    public class Clazz {
        private String field;
    } 
    

    Of course, you could still have some private method that modifies the field directly, but it would be very unlikely to even have any actual code in a @Data POJO, so this would hopefully not happen.

    Disclaimer: This will have the side-effect (perhaps beneficial) of not letting regular Java code create the object since there is only a default constructor with no mutators. To allow for normal construction you will need 2 more annotations:

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    @Setter(AccessLevel.NONE)
    public class Clazz {
        private String field;
    } 
    

提交回复
热议问题