BeanUtils(利用反射实现对象间相同属性的复制)

话不多说直接贴代码

	/**
     * 利用反射实现对象之间相同属性复制
     *
     * @param source
     *            要复制的
     * @param target
     *            复制给
     */
    public static void copyProperties(Object source, Class<?> fromClass, Object target, Class<?> targetClass)
            throws Exception {

        copyPropertiesExclude(source, fromClass, target, targetClass);
    }

	/**
     * 复制对象属性
     *
     * @param from
     * @param to
     * @param excludsArray
     *            排除属性列表
     * @throws Exception
     */
    public static void copyPropertiesExclude(Object from, Class<?> fromClass, Object to, Class<?> toClass) throws Exception {

        Method[] fromMethods = fromClass.getDeclaredMethods();
        Method[] toMethods = fromClass.getDeclaredMethods();
        Method fromMethod = null, toMethod = null;
        String fromMethodName = null, toMethodName = null;

        for (int i = 0; i < fromMethods.length; i++) {

            fromMethod = fromMethods[i];
            fromMethodName = fromMethod.getName();

            if (!fromMethodName.contains("get"))
                continue;
                
            toMethodName = "set" + fromMethodName.substring(3);
            toMethod = findMethodByName(toMethods, toMethodName);

            if (toMethod == null)
                continue;
            // 通过对象返回获取该方法的值
            Object value = fromMethod.invoke(from, new Object[0]);

            if (value == null)
                continue;
            // 集合类判空处理
            if (value instanceof Collection) {

                Collection<?> newValue = (Collection<?>) value;

                if (newValue.size() <= 0)
                    continue;
            }

            toMethod.invoke(to, new Object[] { value });
        }
    }
	/**
     * 从方法数组中获取指定名称的方法
     *
     * @param methods
     * @param name
     * @return
     */
    public static Method findMethodByName(Method[] methods, String name) {

        for (int j = 0; j < methods.length; j++) {

            if (methods[j].getName().equals(name)) {

                return methods[j];
            }

        }
        return null;
    }

下面是测试:

	public static void main(String[] args) throws Exception {
        NewsType newsType = new NewsType();
        newsType.setName("测试反射");
        newsType.setCreatedByID(12138L);
        newsType.setCreatedByName("ZJH");
        newsType.setCreatedOn(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2018-11-05 12:12:59"));
        newsType.setCode("12138");

        NewsType type = new NewsType();
        BeanUtil.copyProperties(newsType,NewsType.class,type,NewsType.class);

        System.out.println(type.getCreatedByName()+"  "+type.getCode()+"  "+type.getName()+"  "+type.getCreatedByID());

    }

控制台输出为:ZJH 12138 测试反射 12138

猜你喜欢

转载自blog.csdn.net/qq_40962552/article/details/83825546