简体   繁体   中英

Lombok @Wither, @Value, @NoArgsConstructor, @AllArgsConstructor do not work together

I am writing a simple model as below. I can see the wither function in intellij structure view. but compiler complains about "variable field1 might not have been initialized"

@Wither
@Value
@NoArgsConstructor
@AllArgsConstructor
public class MyModel {
    String field1;
    String field2;
}

If I initialize the fields, I donot see wither functions anymore. What could be happening here?

As from the documentation :

@Value is the immutable variant of @Data ; all fields are made private and final by default, and setters are not generated.


So String field1 becomes final String field1 .

Since you are also using @NoArgsConstructor Java compiler complains that "variable field1 might not have been initialized", which is true, since somewhere in the code you can do

MyModel model = new MyModel();

and since the constructor does not initialize any fields, Java complains.

From Final (Java) wiki:

A final variable can only be initialized once, either via an initializer or an assignment statement. It does not need to be initialized at the point of declaration: this is called a "blank final" variable. A blank final instance variable of a class must be definitely assigned in every constructor of the class in which it is declared; similarly, a blank final static variable must be definitely assigned in a static initializer of the class in which it is declared; otherwise, a compile-time error occurs in both cases.


And this is exactly what happens in your case.

You can use @Data instead of @Value , and all other parts are the same.

@Data
@AllArgsConstructor
@NoArgsConstructor
public class MyModel {
    String field1;
    String field2;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM