1. 程式人生 > >BeanUtils(利用反射實現物件間相同屬性的複製)

BeanUtils(利用反射實現物件間相同屬性的複製)

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