BeanUtils工具

package com.demo.common.utils;

import org.apache.commons.beanutils.BeanUtilsBean;
import org.apache.commons.beanutils.ConvertUtilsBean;
import org.apache.commons.beanutils.PropertyUtilsBean;
import org.apache.commons.beanutils.converters.DateConverter;
import org.apache.commons.beanutils.converters.LongConverter;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.UndeclaredThrowableException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;


public class BeanUtils {
    private static Logger logger = LoggerFactory.getLogger(BeanUtils.class);
    public final static ConvertUtilsBean convertUtilsBean = new ConvertUtilsBean();
    private static BeanUtilsBean beanUtilsBean;

    private static ConcurrentHashMap<String, Constructor> constructorCache = new ConcurrentHashMap();

    static {
        beanUtilsBean = new BeanUtilsBean(convertUtilsBean, new PropertyUtilsBean());
        convertUtilsBean.register(new DateConverter(), Date.class);
        convertUtilsBean.register(new LongConverter(null), Long.class);
    }

    public BeanUtils() {
    }

    public static <T> void setValueIgnoreEmpty(T value, Consumer<T> consumer){
        if(BeanUtils.isNotEmpty(value)){
            consumer.accept(value);
        }
    }

    public static <T> void setValue(T value, Consumer<T> consumer){
        consumer.accept(value);
    }

    public static <T> void setValueElseEmpty(T value,T defaultValue, Consumer<T> consumer){
        if(BeanUtils.isNotEmpty(value)){
            consumer.accept(value);
        }else{
            consumer.accept(defaultValue);
        }
    }

    public static <T> T getValueElseDefault(T value,T defaultValue){
        if(BeanUtils.isNotEmpty(value)){
            return value;

        }else{
            return defaultValue;
        }
    }


    public static boolean isEmpty(Object o) {
        if (o == null) {
            return true;
        } else {
            if (o instanceof String) {
                if (((String) o).trim().length() == 0) {
                    return true;
                }
            } else if (o instanceof Collection) {
                if (((Collection) o).isEmpty()) {
                    return true;
                }
            } else if (o.getClass().isArray()) {
                if (((Object[]) o).length == 0) {
                    return true;
                }
            } else if (o instanceof Map) {
                if (((Map) o).isEmpty()) {
                    return true;
                }
            } else if (o instanceof Long) {
                /*Long sEmpty2 = Long.valueOf(0L);
                if (sEmpty2.equals(o)) {
                    return true;
                }*/
            } else if (o instanceof Short) {
                /*Short sEmpty1 = Short.valueOf((short) 0);
                if (sEmpty1.equals(o)) {
                    return true;
                }*/
            } else if (o instanceof Integer) {
                /*Integer sEmpty = Integer.valueOf(0);
                if (sEmpty.equals(o)) {
                    return true;
                }*/
            }

            return false;
        }
    }

    public static boolean isNotEmpty(Object o) {
        return !isEmpty(o);
    }

    public static boolean isNotEmpty(Long o) {
        return !isEmpty(o);
    }

    public static boolean isNumber(Object o) {
        if (o == null) {
            return false;
        } else if (o instanceof Number) {
            return true;
        } else if (o instanceof String) {
            try {
                Double.parseDouble((String) o);
                return true;
            } catch (NumberFormatException var2) {
                return false;
            }
        } else {
            return false;
        }
    }

    public static Object populateEntity(Map<String,Object> map, Object entity) throws IllegalAccessException, InvocationTargetException {
        beanUtilsBean.populate(entity, map);
        return entity;
    }

    public static boolean validClass(String className) {
        try {
            Class.forName(className);
            return true;
        } catch (ClassNotFoundException var2) {
            return false;
        }
    }

    public static boolean isInherit(Class<?> cls, Class parentClass) {
        return parentClass.isAssignableFrom(cls);
    }

    public static Object cloneBean(Object bean) {
        try {
            return beanUtilsBean.cloneBean(bean);
        } catch (Exception var2) {
            handleReflectionException(var2);
            return null;
        }
    }


    public static <T> T copyProperties(Class<T> destClass, Object orig) {
        T target = null;

        try {
            target = destClass.newInstance();
            copyProperties(target, orig);
            return target;
        } catch (Exception var4) {
            handleReflectionException(var4);
            return null;
        }
    }

    public static void copyProperties(Object dest, Object orig) {
        try {
            beanUtilsBean.copyProperties(dest, orig);
        } catch (Exception var3) {
            handleReflectionException(var3);
        }

    }

    public static <T> List<T> copyList(List sourceList, Class<T> targetClass) {
        if (CollectionUtils.isEmpty(sourceList)) {
            return Collections.emptyList();
        }
        List<T> resultList = new ArrayList<>(sourceList.size());
        Constructor<T> constructor = getConstructor(targetClass);
        try {
            for (Object o : sourceList) {
                T t = constructor.newInstance();
                copyProperties(t, o);
                resultList.add(t);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return resultList;
    }

    /**
     * 获取Constructor并缓存
     *
     * @param targetClass
     * @param <T>
     * @return
     */
    private static <T> Constructor<T> getConstructor(Class<T> targetClass) {
        String key = targetClass.toString();
        Constructor constructor = null;
        if (!constructorCache.containsKey(key)) {
            try {
                constructor = targetClass.getConstructor();
                constructorCache.put(key, constructor);
            } catch (NoSuchMethodException e) {
                throw new RuntimeException(e);
            }
        } else {
            constructor = constructorCache.get(key);
        }
        return constructor;
    }

    public static void copyProperty(Object bean, String name, Object value) {
        try {
            beanUtilsBean.copyProperty(bean, name, value);
        } catch (Exception var4) {
            handleReflectionException(var4);
        }

    }

    public static Map describe(Object bean) {
        try {
            return beanUtilsBean.describe(bean);
        } catch (Exception var2) {
            handleReflectionException(var2);
            return null;
        }
    }

    public static String[] getArrayProperty(Object bean, String name) {
        try {
            return beanUtilsBean.getArrayProperty(bean, name);
        } catch (Exception var3) {
            handleReflectionException(var3);
            return null;
        }
    }

    public static ConvertUtilsBean getConvertUtils() {
        return beanUtilsBean.getConvertUtils();
    }

    public static String getIndexedProperty(Object bean, String name, int index) {
        try {
            return beanUtilsBean.getIndexedProperty(bean, name, index);
        } catch (Exception var4) {
            handleReflectionException(var4);
            return null;
        }
    }

    public static String getIndexedProperty(Object bean, String name) {
        try {
            return beanUtilsBean.getIndexedProperty(bean, name);
        } catch (Exception var3) {
            handleReflectionException(var3);
            return null;
        }
    }

    public static String getMappedProperty(Object bean, String name, String key) {
        try {
            return beanUtilsBean.getMappedProperty(bean, name, key);
        } catch (Exception var4) {
            handleReflectionException(var4);
            return null;
        }
    }

    public static String getMappedProperty(Object bean, String name) {
        try {
            return beanUtilsBean.getMappedProperty(bean, name);
        } catch (Exception var3) {
            handleReflectionException(var3);
            return null;
        }
    }

    public static String getNestedProperty(Object bean, String name) {
        try {
            return beanUtilsBean.getNestedProperty(bean, name);
        } catch (Exception var3) {
            handleReflectionException(var3);
            return null;
        }
    }

    public static String getProperty(Object bean, String name) {
        try {
            return beanUtilsBean.getProperty(bean, name);
        } catch (Exception var3) {
            handleReflectionException(var3);
            return null;
        }
    }

    public static PropertyUtilsBean getPropertyUtils() {
        try {
            return beanUtilsBean.getPropertyUtils();
        } catch (Exception var1) {
            handleReflectionException(var1);
            return null;
        }
    }

    public static String getSimpleProperty(Object bean, String name) {
        try {
            return beanUtilsBean.getSimpleProperty(bean, name);
        } catch (Exception var3) {
            handleReflectionException(var3);
            return null;
        }
    }

    public static void populate(Object bean, Map<String,Object> properties) {
        try {
            beanUtilsBean.populate(bean, properties);
        } catch (Exception var3) {
            handleReflectionException(var3);
        }

    }

    public static void setProperty(Object bean, String name, Object value) {
        try {
            beanUtilsBean.setProperty(bean, name, value);
        } catch (Exception var4) {
            handleReflectionException(var4);
        }

    }

    private static void handleReflectionException(Exception ex) {
        if (ex instanceof NoSuchMethodException) {
            throw new IllegalStateException("Method not found: " + ex.getMessage());
        } else if (ex instanceof IllegalAccessException) {
            throw new IllegalStateException("Could not access method: " + ex.getMessage());
        } else {
            if (ex instanceof InvocationTargetException) {
                handleInvocationTargetException((InvocationTargetException) ex);
            }

            if (ex instanceof RuntimeException) {
                throw (RuntimeException) ex;
            } else {
                throw new UndeclaredThrowableException(ex);
            }
        }
    }

    private static void handleInvocationTargetException(InvocationTargetException ex) {
        rethrowRuntimeException(ex.getTargetException());
    }

    private static void rethrowRuntimeException(Throwable ex) {
        if (ex instanceof RuntimeException) {
            throw (RuntimeException) ex;
        } else if (ex instanceof Error) {
            throw (Error) ex;
        } else {
            throw new UndeclaredThrowableException(ex);
        }
    }

    /**
     判断两个字符串或者整型对象是否相等
     */
    public static boolean judgeTwoStringOrIntegerIsEqual(Object o1, Object o2) {
        if(o1 == null && o2 == null) {
            return true;
        }
        if(o1 != null && o2 == null) {
            if(o1 instanceof String && StringUtils.isEmpty((String)o1)){
                return true;
            } else {
                return false;
            }
        }
        if(o1 == null && o2 != null) {
            if(o2 instanceof String && StringUtils.isEmpty((String)o2)){
                return true;
            } else {
                return false;
            }
        }
        if(o1 instanceof Integer && o2 instanceof Integer) {
            if(o1.equals(o2)){
                return true;
            }
        }
        if(o1 instanceof String && o2 instanceof String) {
            if(o1.equals(o2)){
                return true;
            }
        }
        if(o1 instanceof Date && o2 instanceof Date) {
            String date1 = DateUtil.format((Date)o1, DateUtil.YYYYMMDD_SLASH);
            String date2 = DateUtil.format((Date)o2, DateUtil.YYYYMMDD_SLASH);
            if(date1.equals(date2)){
                return true;
            }
        }
        return false;
    }

    /**
     判断两个List是否相等
     */
    public static boolean judgeTwoListIsEqual(List<? extends Object> serv1, List<? extends Object> serv2){

        try{
            if(serv1 == null && serv2 == null){
                return true;
            }
            if(serv1 == null){
                return false;
            }
            if(serv2 == null){
                return false;
            }
            if(serv1.size() != serv2.size()){
                return false;
            } else {
                for(Object iter: serv1){
                    if(!serv2.contains(iter)){
                        return false;
                    }
                }
            }
            return true;
        } catch(NullPointerException e){
            return false;
        }
    }
}

例1、copyProperties:拷贝字段,两个对象字段一致,实现值拷贝::

UserDO userDo= new UserDO();
BeanUtils.copyProperties(userDouserDo,userVO);

例2、setValueElseEmpty:set值,并设置默认值:

 //拼接每行数据
List<String> strings = new ArrayList<>();
BeanUtils.setValueElseEmpty(tableVO.getUserName(), "--", strings::add);

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

w_t_y_y

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值