package com.cjavapy.utils.util;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;
import org.apache.commons.beanutils.PropertyUtils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
public final class ApacheBeanConvertUtil {
private ApacheBeanConvertUtil() {
}
static {
ConvertUtils.register(new Converter() {
public Object convert(Class type, Object value) {
Date date1 = null;
if (value instanceof String) {
String date = (String) value;
SimpleDateFormat sdf = null;
if (date.contains(":")) {
sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
} else {
sdf = new SimpleDateFormat("yyyy-MM-dd");
}
try {
date1 = sdf.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
return date1;
}
return value;
}
}, Date.class);
ConvertUtils.register(new Java110StringConvert(), String.class);
}
public static T2 covertBean(T1 orgBean, T2 dstBean) {
try {
BeanUtils.copyProperties(dstBean, orgBean);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("bean转换bean失败", e);
}
return dstBean;
}
public static T2 covertBean(T1 orgBean, Class t) {
T2 returnModel = null;
try {
returnModel = t.newInstance();
BeanUtils.copyProperties(returnModel, orgBean);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("bean转换bean失败", e);
}
return returnModel;
}
public static List covertBeanList(List orgBeans, Class t) {
List newBeanList = new ArrayList();
for (T1 orgbean : orgBeans) {
T2 newBean = covertBean(orgbean, t);
newBeanList.add(newBean);
}
return newBeanList;
}
public static Map beanCovertMap(Object orgBean) {
Map newMap = null;
try {
newMap = PropertyUtils.describe(orgBean);
} catch (Exception e) {
throw new RuntimeException("bean转换Map失败", e);
}
return newMap;
}
public static List> beanCovertMapList(List orgBeans) {
List> newMaps = new ArrayList>();
Map newMap = null;
for (Object orgbean : orgBeans) {
newMap = beanCovertMap(orgbean);
newMaps.add(newMap);
}
return newMaps;
}
}