我在自定义转换器的文档中读到,对于字段映射的自定义转换器,我可以传递自定义参数。 这对我来说不够好,因为在构建映射器时会指定一次。
在进行实际映射时,有没有办法传递此参数?
mapper.map(sourceObject, Destination.class, "parameter");
我的实际问题是我想要从包含多语言属性的一个类映射,目标应该只有“选择”语言属性。
来源类
public class Source
{
// Fields in default language
private String prop1;
private String prop2;
// List containing all translations of properties
private List<SourceName> sourceNames;
}
public class SourceName
{
private int lang_id;
private String prop1;
private String prop2;
}
目的地类
public class Destination
{
// Fields translated in choosen language
private String prop1;
private String prop2;
}
我的目标是能够这样做:
Destination destination = mapper.map(source, Destination.class, 4); // To lang_id 4
由于
答案 0 :(得分:1)
我已经完成了这个功能(FIELDMAP var是“fieldMap”):
public static <T> T mapWithParam(Object source, Class<T> destinationClass, String param) throws MappingException {
T toReturn = null;
DozerBeanMapper dbm = (DozerBeanMapper) MapperFactory.getMapper();
MappingMetadata mmdt = dbm.getMappingMetadata();
ClassMappingMetadata classMapping = mmdt.getClassMapping(source.getClass(), destinationClass);
List<FieldMappingMetadata> fielMappingMetadata = classMapping.getFieldMappings();
List<OriginalFieldMap> originalValues = new ArrayList<OriginalFieldMap>();
for (FieldMappingMetadata fmmd : fielMappingMetadata) {
if (fmmd.getCustomConverter() != null) {
try {
Class<?> cls = Class.forName(fmmd.getCustomConverter());
if (cls.newInstance() instanceof ConfigurableCustomConverter) {
FieldMap modifieldFieldMap = (FieldMap)ReflectionHelper.executeGetMethod(fmmd, FIELDMAP);
originalValues.add(new OriginalFieldMap(modifieldFieldMap, modifieldFieldMap.getCustomConverterParam()));
modifieldFieldMap.setCustomConverterParam(param);
ReflectionHelper.executeSetMethod(fmmd, FIELDMAP, modifieldFieldMap);
}
} catch (ReflectionException | ClassNotFoundException | InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
}
}
toReturn = dbm.map(source, destinationClass);
for (OriginalFieldMap ofp : originalValues) {
ofp.getFieldMap().setCustomConverterParam(ofp.getOriginalValue());
}
return toReturn;
}
和OriginalFieldMap类:
import org.dozer.fieldmap.FieldMap;
public class OriginalFieldMap{
FieldMap fieldMap;
String originalValue;
public OriginalFieldMap(FieldMap fieldMap, String originalValue) {
super();
this.fieldMap = fieldMap;
this.originalValue = originalValue;
}
public FieldMap getFieldMap() {
return fieldMap;
}
public String getOriginalValue() {
return originalValue;
}
}