0

Is it possible with additional configuration etc to have both @Value and @NoArgsConstructor on a pojo. Something like below.

@Value
@NoArgsConstructor
public class TestClass implements Serializable {

    private String x;
    private String y;
    private String z;

}

For the above class intelij gives compilation error - Variable 'x', 'y', 'z' might not have been initialized etc.

I will appreciate if you can give a working pojo as example.

Work Arounds -

  1. I know i can use something like below as a work around-

    @NoArgsConstructor @AllArgsConstructor @Getter public class TestClass implements Serializable {

         private String x;
         private String y;
         private String z;
    
     }
    
  2. I need the @NoArgsConstructor as jackson needs it. I could find other ways to handle immutable classes with jackson - 1 and 2. But would still prefer to handle it through lombok if it's possible.

samshers
  • 1
  • 6
  • 37
  • 84
  • Jackson does _not_ need a default/no-args constructor, see https://stackoverflow.com/questions/51464720/lombok-1-18-0-and-jackson-2-9-6-not-working-together/51465038#51465038 – Jan Rieke Oct 07 '22 at 13:57
  • @JanRieke, thanks +1. Plz see my edit. I could see other ways to deal with problem.. but I still want to explore a solution based on `lombok`. – samshers Oct 07 '22 at 18:02
  • The link above is a solution with Lombok. – Jan Rieke Oct 07 '22 at 23:32

1 Answers1

1

One solution is to use @Jacksonized, as shown in @Dusan.czh's answer.

In your case the class would look like this:

import lombok.Value;
import lombok.Builder;
import lombok.extern.jackson.Jacksonized;

@Jacksonized
@Builder
@Value
public class TestClass {
    String x;
    String y;
    String z;
}

@Value already marks non-static, package-local fields private and final, so there is no need for private access modifier.

Toni
  • 3,296
  • 2
  • 13
  • 34
  • from lombok docs - `@Jacksonized was introduced as experimental feature in lombok v1.18.14` - i have to update to this version.. +1 – samshers Oct 11 '22 at 10:32