0

我在自定义转换器的文档中读到,对于字段映射上的自定义转换器,我可以传递自定义参数。这对我来说还不够好,因为在构建映射器时已指定一次。

在进行实际映射时有什么方法可以传递这个参数吗?

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

谢谢

4

1 回答 1

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;
    }
}
于 2013-07-18T12:30:22.880 回答