您可以使用org.dozer.converters.PrimitiveOrWrapperConverter
而不是org.dozer.DozerBeanMapper
:
import org.dozer.converters.DateFormatContainer;
import org.dozer.converters.PrimitiveOrWrapperConverter;
public class DozerPrimitiveMapping {
public static void main(String[] args) {
PrimitiveOrWrapperConverter primitiveConverter = new PrimitiveOrWrapperConverter();
//DateFormatContainer is not needed in this String-to-Boolean use case, but the converter would throw an error if it was null
DateFormatContainer dateFormatContainer = new DateFormatContainer("");
Boolean booleanResult= (Boolean) primitiveConverter.convert("true", Boolean.class, dateFormatContainer);
System.out.println("Boolean result from dozer: "+booleanResult);
}
}
或者将其全部包装在自定义转换器中:
package my.dozer.test;
import org.dozer.CustomConverter;
import org.dozer.converters.DateFormatContainer;
import org.dozer.converters.PrimitiveOrWrapperConverter;
public class DozerPrimitiveConverter implements CustomConverter {
private final PrimitiveOrWrapperConverter primitiveConverter = new PrimitiveOrWrapperConverter();
//DateFormatContainer is not needed in this String-to-Boolean use case, but the converter would throw an error if it was null
private final DateFormatContainer dateFormatContainer = new DateFormatContainer("");
@Override
public Object convert(Object existingDestinationFieldValue, Object sourceFieldValue, Class<?> destinationClass, Class<?> sourceClass) {
Boolean booleanResult = (Boolean) primitiveConverter.convert(sourceFieldValue, Boolean.class, dateFormatContainer);
return booleanResult;
}
}
并像在此示例配置文件中一样配置转换器dozer-primitive-mapping.xml
:
<?xml version="1.0" encoding="UTF-8"?>
<mappings xmlns="http://dozer.sourceforge.net"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://dozer.sourceforge.net
http://dozer.sourceforge.net/schema/beanmapping.xsd">
<configuration>
<custom-converters>
<converter type="my.dozer.test.DozerPrimitiveConverter" >
<class-a>java.lang.String</class-a>
<class-b>java.lang.Boolean</class-b>
</converter>
</custom-converters>
</configuration>
</mappings>
使用自定义转换器运行映射的示例类:
package my.dozer.test;
import java.io.InputStream;
import org.dozer.DozerBeanMapper;
public class DozerPrimitiveConverterApp {
public static void main(String[] args) {
DozerBeanMapper mapper = new DozerBeanMapper();
InputStream is = DozerPrimitiveConverterApp.class.getClassLoader().getResourceAsStream("dozer-primitive-mapping.xml");
mapper.addMapping(is);
Boolean booleanValue = mapper.map("false", Boolean.class);
System.out.println("Boolean result from dozer with custom converter: " + booleanValue);
}
}