我想通过自定义Converter将source
中的字段映射到现有对象dest
中。您能否建议一种规范的方法来从dest
伸出AbstractConverter#convert()
对象
请在下面找到代码:
Source source = new Source(xxx);
Dest dest = new Dest(yyy);
modelMapper.addConverter(new AbstractConverter<Source, Dest>() {
@Override
protected Dest convert(Source source) {
// here I need to access 'dest' object in order to manually map fields from 'source'
});
modelMapper.map(source, dest);
答案 0 :(得分:1)
如果要访问目标对象,则不应使用AbstractConverter,而应使用匿名Converter:
modelMapper.addConverter(new Converter<Source, Dest>() {
public Dest convert(MappingContext<Source, Dest> context) {
Source s = context.getSource();
Dest d = context.getDestination();
d.setYyy(s.getXxx() + d.getYyy()); // example of using dest's existing field
return d;
}
});
答案 1 :(得分:0)
将Dest dest = new Dest(yyy)
移到新的AbstractConvertor主体中。
modelMapper.addConverter(new AbstractConverter<Source, Dest>() {
private Dest dest = new Dest(yyy);
@Override
protected Dest convert(Source source) {
// here I need to access 'dest' object in order to manually map fields from 'source'
});