新增beanToBean方法
This commit is contained in:
parent
6a0702fb16
commit
3de938dd2a
@ -2,6 +2,7 @@ package ink.wgink.util;
|
|||||||
|
|
||||||
import org.apache.commons.lang3.StringUtils;
|
import org.apache.commons.lang3.StringUtils;
|
||||||
|
|
||||||
|
import java.lang.reflect.Field;
|
||||||
import java.lang.reflect.InvocationTargetException;
|
import java.lang.reflect.InvocationTargetException;
|
||||||
import java.lang.reflect.Method;
|
import java.lang.reflect.Method;
|
||||||
|
|
||||||
@ -65,6 +66,40 @@ public class ReflectUtil {
|
|||||||
return (T) singleInstanceObject;
|
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 static class ReflectException extends ReflectiveOperationException {
|
||||||
|
|
||||||
public ReflectException() {
|
public ReflectException() {
|
||||||
|
Loading…
Reference in New Issue
Block a user