I almost wrote what I wanted to say in the title. That's all I want to say in this article:
It is the behavior in Lombok 1.16.18.
import lombok.*;
@Data
public class Test {
private final int value1;
private final int value2;
public static void main(String[] args){
new Test(1, 1);
}
}
In this case, @Data bundles @RequiredArgsConstructor, so the constructor is generated and compiled.
However, this bundled @RequiredArgsConstructor will only generate a constructor if there is no explicit constructor declaration. This is normal behavior as described in the documentation.
(except that no constructor will be generated if any explicitly written constructors already exist). Quoted from @Data
For example, the following code will not compile.
import lombok.*;
@Data
public class Test {
private final int value1;
private final int value2;
public static void main(String[] args){
new Test(1, 1);
}
//Explicit constructor
public Test() {
}
}
Even if you add an annotation that generates a constructor such as @NoArgsConstructor, the constructor will not be generated by @Data as well. Therefore, the following code will not compile.
import lombok.*;
@NoArgsConstructor
@Data
public class Test {
private final int value1;
private final int value2;
public static void main(String[] args){
new Test(1, 1);
}
}
With both @Data and @Value, @AllArgsConstructor seems to win.
import lombok.*;
import java.util.Arrays;
@Data
@Value
public class Test {
int value1;
int value2;
public static void main(String[] args){
Arrays.stream(Test.class.getConstructors()).forEach(System.out::println);
new Test(1, 1); //This passes
new Test(); //This does not pass
}
}
I also tried the explicit constructor + @ Data + @ Value, but none of them were generated.
import lombok.*;
import java.util.Arrays;
@Value
@Data
public class Test {
int value1;
int value2;
public static void main(String[] args){
Arrays.stream(Test.class.getConstructors()).forEach(System.out::println);
}
//Explicit constructor
public Test(int i){
}
}