给出以下两种方法(不是可编译的代码,只是结构):
protected String mapABC(
Entity entity, @Context MappingContext mappingContext) {
return Optional.ofNullable(getSomething(entity))
.map(
x -> getBlah(x::getName))
.orElse(null);
}
protected String mapXYZ(
Entity entity, @Context MappingContext mappingContext) {
return Optional.ofNullable(getSomething(entity))
.map(
x -> getBlah(x::getFirstName))
.orElse(null);
}
我正在考虑避免重复逻辑时会是什么样子,这样就可以编写类似这样的结构:
protected String mapXYZ(
Entity entity, @Context MappingContext mappingContext) {
return xxx(getName());
}
protected String mapXYZ(
Entity entity, @Context MappingContext mappingContext) {
return xxx(getFirsName());
}
private String xxx(Methodreference m){
return Optional.ofNullable(getSomething(entity))
.map(
x -> getBlah(x::m))
.orElse(null);
}
x 的类型是:
@AllArgsConstructor
@NoArgsConstructor
@Data
@Builder(toBuilder = true)
public class DetailData {
private String name;
private String firstname;
}
我有什么可以尝试的想法吗?
你应该采取
Function<DetailData, String>
private String map(Function<DetailData, String> m){
return Optional.ofNullable(getSomething(entity))
.map(
x -> getBlah(m.apply(x)))
.orElse(null);
}
用途:
protected String mapXYZ(
Entity entity, @Context MappingContext mappingContext) {
return map(DetailData::getName);
}
protected String mapXYZ(
Entity entity, @Context MappingContext mappingContext) {
return map(DetailData::getFirstName);
}