新增beanToBean方法

This commit is contained in:
wanggeng888 2021-04-13 19:12:57 +08:00
parent 6a0702fb16
commit 3de938dd2a

View File

@ -2,6 +2,7 @@ package ink.wgink.util;
import org.apache.commons.lang3.StringUtils;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
@ -65,6 +66,40 @@ public class ReflectUtil {
return (T) singleInstanceObject;
}
/**
* bean转bean相同属性的值可以相互复制
*
* @param srcBean 源bean
* @param destBeanClass 转换后的bean类
* @param <T>
* @return
* @throws ReflectException
*/
public static <T> T beanToBean(Object srcBean, Class<T> destBeanClass) throws ReflectException {
try {
Field[] srcFieldArray = srcBean.getClass().getDeclaredFields();
Field[] destFieldArray = destBeanClass.getDeclaredFields();
T t = destBeanClass.newInstance();
for (Field field : srcFieldArray) {
for (Field destField : destFieldArray) {
String destFieldName = destField.getName();
if (!StringUtils.equals(field.getName(), destFieldName)) {
continue;
}
String firstLetter = destFieldName.substring(0, 1).toUpperCase();
String firstUpperMethodName = firstLetter + destFieldName.substring(1, destFieldName.length());
Method getMethod = srcBean.getClass().getMethod("get" + firstUpperMethodName);
Object value = getMethod.invoke(srcBean);
Method setMethod = destBeanClass.getMethod("set" + firstUpperMethodName, value.getClass());
setMethod.invoke(t, value);
}
}
return t;
} catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
throw new ReflectException(e.getMessage(), e);
}
}
public static class ReflectException extends ReflectiveOperationException {
public ReflectException() {