搬砖_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);
        }
    }
}

</t2></t1></t2></t1,>

Original: https://www.cnblogs.com/deanCopy/p/16337847.html
Author: Dean_001
Title: 搬砖_BeanUtils的扩展

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/714443/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球