Lombok's @Value and @Data do not generate a constructor if another explicit constructor is declared

What's the story

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.

Normal usage

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.

Case where the constructor is not generated

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

Example (explicit constructor declaration)

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() {

	}
}

Example (Generation of constructor by annotation)

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){

	}
}

Recommended Posts

Lombok's @Value and @Data do not generate a constructor if another explicit constructor is declared
[Rails] What to do if data is not registered in DB
What to do if the breakpoint is shaded and does not stop during debugging