Reputation: 1876
I read in the documentation of custom converter that for a custom converter on a field mapping I can pass a custom parameter. This is not good enough for me because this is specified once when building the mapper.
Is there any way to pass this parameter when doing the actual mapping?
mapper.map(sourceObject, Destination.class, "parameter");
My actual problem is that I want to map from one class containing multi lingual properties and destination should only have the "choosen" language properties.
Source class
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;
}
Destination class
public class Destination
{
// Fields translated in choosen language
private String prop1;
private String prop2;
}
My goal is to be able to do like this:
Destination destination = mapper.map(source, Destination.class, 4); // To lang_id 4
Thanks
Upvotes: 0
Views: 2299
Reputation: 72
I have made this function (FIELDMAP var is "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;
}
And OriginalFieldMap class:
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;
}
}
Upvotes: 1