一、copyProperties
BeanUtils.copyProperties(source, target);
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);
二、populate
1、介绍
BeanUtils.populate(Object bean, Map properties) 方法实在org.apache.commons.beanutils.BeanUtils包下的一个一个方法。
该方法的方法头
此方法中,有两个参数,Object bean 为一个实体类,Map properties为一个map集合,调用此方法的执行过程为
(1)遍历Map集合中的key
(2)判断bean实体中是否有相应的属性
(3)如果有与bean中对应的属性
(4)将与Map集合中对应的value值赋值个bean中的相应的属性
2、demo
Map<String,Object> beanProperMap =new HashMap<>();
beanProperMap.put("name","这是name");
beanProperMap.put("url","这是url");
MenuDTO bean = MenuDTO.builder().build();
BeanUtils.populate(bean,beanProperMap);
System.out.println(bean);
输出:
MenuDTO(name=这是name, url=这是url)