我正在使用Java的https://immutables.github.io/,并且在使用基类和设置其字段一次时遇到麻烦。
我有不可变对象,它们利用Egg模式共享字段,例如:
interface HousingBase {
int streetNumber();
String streetName();
int zip();
}
@Value.Immutable
interface House extends HousingBase {
long lotSize();
}
@Value.Immutable
interface Apartment extends HousingBase {
int apartmentNumber();
}
问题是我的代码从一组HousingBase
字段构造这些对象,而我最终得到重复的代码,例如:
public ImmutableHouse toHouse(HouseLocation location) {
return ImmutableHouse.builder()
.setStreetNumber(location.number())
.setStreetName(location.street())
.setZip(location.zip())
.setLotSize(location.size())
.build();
}
public ImmutableApartment toHouse(ApartmentLocation location) {
return ImmutableApartment.builder()
.setStreetNumber(location.number())
.setStreetName(location.street())
.setZip(location.zip())
.setApartmentNumber(location.complex())
.build();
}
我真正想要的是某种方法来设置HousingBase
字段,以便对它们进行一次定义。像这样:
public ImmutableApartment toHouse(ApartmentLocation location) {
return setBaseFields(ImmutableApartment.builder(), location)
.setApartmentNumber(location.complex())
.build();
}
private Builder setBaseFields(Builder builder, Location location) {
return builder
.setStreetNumber(location.number())
.setStreetName(location.street())
.setZip(location.zip())
}
但是我不知道如何使它正常工作,或者在此库中是否可行。
泛型!
private static <B extends Builder> B setBaseFields(B builder, Location location) {