1、简介
dozer是一种JavaBean的映射工具,类似于apache的BeanUtils。但是dozer更强大,它可以灵活的处理复杂类型之间的映射。不但可以进行简单的属性映射、复杂的类型映射、双向映射、递归映射等,并且可以通过XML配置文件进行灵活的配置。
2、准备
现在开始就小试一下。
首先,需要下载jar包,
dozer.jar :http://dozer.sourceforge.net/downloading.html
还需要slf4j.jar,commons-lang.jar,commons-beanutil.jar, commons-loggin.jar
http://lishaorui.iteye.com/blog/1151513
- import com.google.common.collect.Lists;
- import java.util.Collection;
- import java.util.Iterator;
- import java.util.List;
- import org.dozer.DozerBeanMapper;
-
- public class BeanMapper
- {
- private static DozerBeanMapper dozer = new DozerBeanMapper();
-
-
- public static <T> T map(Object source, Class<T> destinationClass)
- {
- return dozer.map(source, destinationClass);
- }
-
-
-
- public static <T> List<T> mapList(Collection sourceList, Class<T> destinationClass)
- {
- List destinationList = Lists.newArrayList();
- for (Iterator i$ = sourceList.iterator(); i$.hasNext(); ) { Object sourceObject = i$.next();
- Object destinationObject = dozer.map(sourceObject, destinationClass);
- destinationList.add(destinationObject);
- }
- return destinationList;
- }
-
-
-
- public static void copy(Object source, Object destinationObject)
- {
- dozer.map(source, destinationObject);
- }
- }
使用:
- SmIaasQuotaV result = null;
- try {
- result = limitService.getLimitDetails(id,parentId);
- if(result != null){
- response.setData(BeanMapper.map(result, Map.class));
- response.setSuccess(true);
- }
- }
BeanMapper.map(result, Map.class)
转换为Map对象。
- public static <T> Map<String, T> toMap(Object target) {
- return toMap(target,false);
- }
-
- public static <T> Map<String, T> toMap(Object target,boolean ignoreParent) {
- return toMap(target,ignoreParent,false);
- }
-
- public static <T> Map<String, T> toMap(Object target,boolean ignoreParent,boolean ignoreEmptyValue) {
- return toMap(target,ignoreParent,ignoreEmptyValue,new String[0]);
- }
-
- public static <T> Map<String, T> toMap(Object target,boolean ignoreParent,boolean ignoreEmptyValue,String... ignoreProperties) {
- Map<String, T> map = new HashMap<String, T>();
-
- List<Field> fields = ReflectionUtils.getAccessibleFields(target.getClass(), ignoreParent);
-
- for (Iterator<Field> it = fields.iterator(); it.hasNext();) {
- Field field = it.next();
- T value = null;
-
- try {
- value = (T) field.get(target);
- } catch (Exception e) {
- e.printStackTrace();
- }
-
- if (ignoreEmptyValue
- && ((value == null || value.toString().equals(""))
- || (value instanceof Collection && ((Collection<?>) value).isEmpty())
- || (value instanceof Map && ((Map<?,?>)value).isEmpty()))) {
- continue;
- }
-
- boolean flag = true;
- String key = field.getName();
-
- for (String ignoreProperty:ignoreProperties) {
- if (key.equals(ignoreProperty)) {
- flag = false;
- break;
- }
- }
-
- if (flag) {
- map.put(key, value);
- }
- }
-
- return map;
- }
DozerBeanMapper + 对象转Map方法
标签:false bar break turn ati 值拷贝 shm 杂类 amp
原文地址:http://www.cnblogs.com/shihaiming/p/7592101.html