如何在 ModelMapper 的 AbstractConverter.convert() 方法中到达目标对象
How to reach destination object in ModelMapper's AbstractConverter.convert() method
我想通过自定义转换器将 source
中的字段映射到现有对象 dest
中。您能否建议一种从 AbstractConverter#convert()
获取 dest
对象的规范方法
请找到下面的代码:
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);
将 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'
});
如果要访问目标对象,则不应使用 AbstractConverter,而应使用匿名转换器:
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;
}
});
我想通过自定义转换器将 source
中的字段映射到现有对象 dest
中。您能否建议一种从 AbstractConverter#convert()
dest
对象的规范方法
请找到下面的代码:
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);
将 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'
});
如果要访问目标对象,则不应使用 AbstractConverter,而应使用匿名转换器:
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;
}
});