ObjectUtils

ObjectUtils工具類
提供1:對象的克隆 2:list對象的克隆 3:mapList克隆 4:isNull判斷
maven依賴

<dependency>
            <groupId>ma.glasnost.orika</groupId>
            <artifactId>orika-core</artifactId>
            <version>1.5.2</version>
        </dependency>

工具類

package org.mall.common.util;

import ma.glasnost.orika.MapperFacade;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.impl.DefaultMapperFactory;
import ma.glasnost.orika.metadata.Type;
import org.springframework.beans.BeanUtils;

import java.util.Collections;
import java.util.List;

public class ObjectUtils {
    private static MapperFacade mapper;

             static {
                 MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
                 mapper = mapperFactory.getMapperFacade();
             }
    /***
     * 業務邏輯判斷
     * 前提條件爲 入參都爲空 也是不相等
     * */
    public static boolean StringsIsEquals(String s1,String s2){
        if (s1==null||s2==null){
            return false;
        }
        return s1.equals(s2);
    }

    public static <S, D> List<D> mapList(List<S> sourceList, Type<S> sourceType, Type<D> destinationType) {

        return mapper.mapAsList(sourceList, sourceType, destinationType);
     }

     public static <S,D> List<D> copyList(Iterable<S> list, Class<D> dType){
        if(list==null){
            return Collections.emptyList();
        }
       return mapper.mapAsList(list,dType);
     }

     public static  <D> D copyObject(Object o, Class<D> dClass){
        if (o==null){
            return null;
        }
         D temp= null;
         try {
             temp = dClass.newInstance();
         } catch (InstantiationException e) {
            return null;
         } catch (IllegalAccessException e) {
            return null;
         }
         BeanUtils.copyProperties(o,temp);
        return  temp;
     }


     public static boolean isNull(Object... o){
        if (o.length==0){
            return true;
        }
        for ( Object o1:o){
            if (o1==null){
                return true;
            }
        }
        return false;
     }

}

使用例子

//定義的一個list集合,接收對象
List<OrderDO> list;
//把list<OrderDO>對象的數據全部拷貝到List<OrderPayAllChartBO>
List<OrderPayAllChartBO> bo=ObjectUtils.copyList(list,OrderPayAllChartBO.class);
//把adminsBannerVO對象的數據拷貝到BannerUpdateDTO 
  public CommonResult<Boolean> update(@RequestBody AdminsBannerVO adminsBannerVO) {
        BannerUpdateDTO bannerUpdateDTO= ObjectUtils.copyObject(adminsBannerVO, BannerUpdateDTO.class);

        return success(bannerService.updateBanner(JwtUtil.getUserIdByToken(), bannerUpdateDTO));
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章