搬砖_BeanUtils的扩展
简单描述一下:
org.apache.commons.beanutils.BeanUtils
只能对单个对象进行复制,如果对列表的话,就得自己遍历,所以扩展一下
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.lang.reflect.Method;
import java.util.List;
import java.util.stream.Collectors;
public class BeanUtilsExtend extends org.apache.commons.beanutils.BeanUtils{
private static final Log log = LogFactory.getLog(BeanUtilsExtend.class);
public static <T1, T2> List<T2> listCopy(List<T1> sourceList, Class<T2> clazz) {
return (List) sourceList.stream().map((source)->{
Object target;
try {
target = clazz.getDeclaredConstructor().newInstance();
} catch (Exception e) {
throw new RuntimeException();
}
beanCopy(source, target);
return target;
}).collect(Collectors.toList());
}
public static void beanCopy(Object fromBean, Object toBean)
{
try
{
fromBean.getClass().getMethods();
Method[] setMethods = toBean.getClass().getMethods();
for (Method setMethod : setMethods) {
if (!setMethod.getName().startsWith("set")) {
continue;
}
String fieldName = setMethod.getName().substring(3);
Method getMethod = null;
try {
getMethod = fromBean.getClass().getMethod("get" + fieldName, new Class[0]);
} catch (NoSuchMethodException localNoSuchMethodException) {
continue;
}
if (getMethod.getReturnType() != setMethod.getParameterTypes()[0])
{
log.warn("Type mismatch when beanCopy: " + getMethod.getReturnType().getCanonicalName() + " -> " + setMethod.getParameterTypes()[0].getCanonicalName());
}
else
{
Object fieldValue = getMethod.invoke(fromBean, null);
setMethod.invoke(toBean, new Object[] { fieldValue });
}
}
} catch (Exception e) {
throw new IllegalArgumentException("beanCopy issue", e);
}
}
}