拷貝對象屬性

        /**
	 * 拷貝屬性到目標對象,如果爲空不拷貝,目標對象屬性有值,則不拷貝該屬性
	 * 
	 * @param source
	 *            待拷貝屬性的對象
	 * @param target
	 *            目標對象
	 * @throws BeansException
	 */
	public static void copyPropertiesExclude(Object source, Object target) throws BeansException {
		if (source == null || target == null) {
			throw new RuntimeException("拷貝和被拷貝對象不能爲空。");
		}
		Class<?> actualEditable = target.getClass();
		PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
		for (PropertyDescriptor targetPd : targetPds) {
			if (targetPd.getWriteMethod() != null) {
				PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
				if (sourcePd != null && sourcePd.getReadMethod() != null) {
					try {
						Method readMethod = sourcePd.getReadMethod();
						if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
							readMethod.setAccessible(true);
						}
						Object value = readMethod.invoke(source);
						// 這裏判斷以下value是否爲空 當然這裏也能進行一些特殊要求的處理 例如綁定時格式轉換等等
						if (value != null) {
							Method targetReadMethod = targetPd.getReadMethod();
							if (!Modifier.isPublic(targetReadMethod.getDeclaringClass().getModifiers())) {
								targetReadMethod.setAccessible(true);
							}
							Object targetValue = targetReadMethod.invoke(target);
							Method writeMethod = targetPd.getWriteMethod();
							if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
								writeMethod.setAccessible(true);
							}
							if(targetValue!=null && !StringUtils.isEmpty(targetValue.toString()) && !"[]".equals(targetValue.toString())){
								continue;
							}
							writeMethod.invoke(target, value);
						}
					} catch (Throwable ex) {
						throw new FatalBeanException("Could not copy properties from source to target", ex);
					}
				}
			}
		}
	}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章