源类:
class ReportSettings {
private HeaderSettings headerSettings;
private FooterSettings footerSettings;
// getters and setters omitted
}
class HeaderSettings {
private boolean showLogo;
// getters and setters omitted
}
class FooterSettings {
private boolean showPageNumber;
// getters and setters omitted
}
目标类别:
class Parameters {
private String group;
private String name;
private String value;
// getters and setters omitted
}
是否可以使用MapStruct将ReportSettings
对象转换为List<Parameters>
对象,如下所示,其中ReportSettings
类的字段名称映射到Parameter
类的{{ 1}}字段:
group
答案 0 :(得分:1)
据我所知,尚无此类功能可根据字段名称动态创建列表。
我想到的唯一想法是一个真正的静态解决方案,但是我想您有一个动态的字段列表,并且不能以这种方式完成。
@Mapper
public abstract class ReportSettingsMapper {
@Mappings({
@Mapping(target = "group", constant = "headerSettings"),
@Mapping(target = "name", constant = "showLogo"),
@Mapping(target = "value", source = "headerSettings.showLogo")
})
protected abstract Parameters mapHeaderSettings(ReportSettings settings);
@Mappings({
@Mapping(target = "group", constant = "footerSettings"),
@Mapping(target = "name", constant = "showPageNumber"),
@Mapping(target = "value", source = "footerSettings.showPageNumber")
})
protected abstract Parameters mapFooterSettings(ReportSettings settings);
public List<Parameters> mapReportSettings(ReportSettings settings) {
List<Parameters> parameters = new ArrayList<>();
parameters.add( mapHeaderSettings(settings) );
parameters.add( mapFooterSettings(settings) );
return parameters;
}
}
(未经测试的代码;如果使用Java> = 8,则可以使用具有默认方法的接口+删除@Mappings
容器注释)