1、复制相应的字段到另一个实例中
2、将bean转换成map
3、根据class创建实例
public class BeanTransferUtils {
private BeanTransferUtils(){
//私有构造
}
public static <T, K> K transferColumn(T source, Class<T> sourceClazz, Class<K> targetClazz) throws CannaException {
if (source == null) {
return getInstance(targetClazz);
}
K targetBean = getInstance(targetClazz);
BeanCopier.create(sourceClazz, targetClazz, false).copy(source, targetBean, null);
return targetBean;
}
public static <T, K> List<K> transferColumn(List<T> sourceList, Class<T> sourceClazz, Class<K> targetClazz) throws CannaException {
if (CollectionUtils.isEmpty(sourceList)) {
return Collections.emptyList();
}
List<K> result = new ArrayList<>();
BeanCopier beanCopier = BeanCopier.create(sourceClazz, targetClazz, false);
K targetBean;
for (T source : sourceList) {
targetBean = getInstance(targetClazz);
beanCopier.copy(source, targetBean, null);
result.add(targetBean);
}
return result;
}
public static <T> Map<String, Object> bean2Map(T bean) {
if (bean == null) {
return Collections.emptyMap();
}
BeanMap beanMap = BeanMap.create(bean);
Map<String,Object> result = new HashMap<>(beanMap.size());
result.putAll(beanMap);
return result;
}
public static <T> T map2Bean(Map<String, Object> sourceMap, Class<T> targetClazz) {
T bean = null;
try {
bean = targetClazz.newInstance();
if (MapUtils.isNotEmpty(sourceMap)) {
BeanMap beanMap = BeanMap.create(bean);
beanMap.putAll(sourceMap);
}
} catch (Exception e) {
log.error("", e);
}
return bean;
}
public static <T> List<Map<String, Object>> beanList2Map(List<T> beanList) {
if (CollectionUtils.isEmpty(beanList)) {
return Collections.emptyList();
}
List<Map<String, Object>> list = new ArrayList<>(beanList.size());
Map<String,Object> result;
if (CollectionUtils.isNotEmpty(beanList)) {
for (T bean : beanList) {
if (bean == null) {
continue;
}
BeanMap beanMap = BeanMap.create(bean);
result = new HashMap<>(beanMap.size());
result.putAll(beanMap);
list.add(result);
}
}
return list;
}
public static <T> T getInstance(Class<T> clazz) throws CannaException {
try {
return clazz.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
log.info("", e);
throw new CannaException(ToolsErrorType.REFLECT_FAIL);
}
}
}