一、簡介
dozer是一種JavaBean的映射工具,相似於apache的BeanUtils。可是dozer更強大,它能夠靈活的處理複雜類型之間的映射。不但能夠進行簡單的屬性映射、複雜的類型映射、雙向映射、遞歸映射等,而且能夠經過XML配置文件進行靈活的配置。
二、準備
如今開始就小試一下。
首先,須要下載jar包,
dozer.jar :http://dozer.sourceforge.net/downloading.html
還須要slf4j.jar,commons-lang.jar,commons-beanutil.jar, commons-loggin.jar html
http://lishaorui.iteye.com/blog/1151513java
- 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);
- }
- }
使用:apache
- 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)app
轉換爲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;
- }