@Builder
无法确定您希望公开哪些字段。Parent
当 放置在类上时,只有在该类上显式声明的字段才会添加到 .@Builder
*Builder
当放置在静态方法或构造函数上时,结果将具有每个参数的方法。@Builder
*Builder
另外,如果您正在使用,那么是否可以安全地假设至少意味着是不可变的?@Builder
Child
我举了两个例子,一个是可变的和不可变的,另一个是两者都是不可变的。Parent
Child
Parent
Child
不可变的父项和子项
import static org.junit.Assert.*;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import lombok.Value;
import lombok.experimental.NonFinal;
import org.junit.Test;
public class So32989562ValueTest {
@Value
@NonFinal
public static class Parent {
protected final String nationality;
}
@Value
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
public static class Child extends Parent {
private final String firstName;
private final String lastName;
@Builder(toBuilder = true)
private Child(String nationality, String firstName, String lastName) {
super(nationality);
this.firstName = firstName;
this.lastName = lastName;
}
}
@Test
public void testChildBuilder() {
String expectedFirstName = "Jeff";
String expectedLastName = "Maxwell";
String expectedNationality = "USA";
Child result = Child.builder()
.firstName(expectedFirstName)
.lastName(expectedLastName)
.nationality(expectedNationality)
.build();
assertEquals(result.toString(), expectedFirstName, result.getFirstName());
assertEquals(result.toString(), expectedLastName, result.getLastName());
assertEquals(result.toString(), expectedNationality, result.getNationality());
}
}
可变父项,不可变子项:
import static org.junit.Assert.*;
import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import lombok.Value;
import org.junit.Test;
public class So32989562DataTest {
@Data
public static class Parent {
protected String nationality;
}
@Value
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
public static class Child extends Parent {
private final String firstName;
private final String lastName;
@Builder(toBuilder = true)
private Child(String nationality, String firstName, String lastName) {
this.setNationality(nationality);
this.firstName = firstName;
this.lastName = lastName;
}
}
@Test
public void testChildBuilder() {
String expectedFirstName = "Jeff";
String expectedLastName = "Maxwell";
String expectedNationality = "USA";
Child result = Child.builder()
.firstName(expectedFirstName)
.lastName(expectedLastName)
.nationality(expectedNationality)
.build();
assertEquals(result.toString(), expectedFirstName, result.getFirstName());
assertEquals(result.toString(), expectedLastName, result.getLastName());
assertEquals(result.toString(), expectedNationality, result.getNationality());
}
}