Could not copy property ‘id‘ from source to target异常

BeanUtils是我们在web开发中经常用到的一个工具类,当一个对象中有多个甚至几十个字段,我们去修改该对象信息时,可能只修改其中的几个或十几个,通过spring的BeanUtils的copyProperties方法可以快速实现,当然,这只是BeanUtils的一个常用功能,更多关于BeanUtils的强大之处可以参考api
http://www.apihome.cn/api/spring/beanutils.html
或是http://blog.csdn.net/shimiso/article/details/5644584

下面说一下今天遇到的异常信息

Could not copy property 'id' from source to target; nested exception is java.lang.IllegalArgumentException

这是之前的po类

Could not copy property ‘id‘ from source to target异常_第1张图片

对比异常信息和这个po类就应该明白怎么一回事了吧

出现问题:在使用BeanUtils.copyProperties()方法时,如果javaBean中的属性含有基本类型,而model模型中对应的属性值为 null 的话,就会出现这个异常。


解决方法:javaBean中的属性值不要使用基本类型。

 

下面附上copyProperty()方法的源码:

private static void copyProperties(Object source, Object target, Class editable, String... ignoreProperties)
			throws BeansException {
 
		Assert.notNull(source, "Source must not be null");
		Assert.notNull(target, "Target must not be null");
 
		Class actualEditable = target.getClass();
		if (editable != null) {
			if (!editable.isInstance(target)) {
				throw new IllegalArgumentException("Target class [" + target.getClass().getName() +
						"] not assignable to Editable class [" + editable.getName() + "]");
			}
			actualEditable = editable;
		}
		PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
		List ignoreList = (ignoreProperties != null ? Arrays.asList(ignoreProperties) : null);
 
		for (PropertyDescriptor targetPd : targetPds) {
			Method writeMethod = targetPd.getWriteMethod();
			if (writeMethod != null && (ignoreList == null || !ignoreList.contains(targetPd.getName()))) {
				PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
				if (sourcePd != null) {
					Method readMethod = sourcePd.getReadMethod();
					if (readMethod != null &&
							ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType())) {
						try {
							if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
								readMethod.setAccessible(true);
							}
							Object value = readMethod.invoke(source);
							if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
								writeMethod.setAccessible(true);
							}
							writeMethod.invoke(target, value);
						}
						catch (Throwable ex) {
							throw new FatalBeanException(
									"Could not copy property '" + targetPd.getName() + "' from source to target", ex);
						}
					}
				}
			}
		}
	}

 

你可能感兴趣的:(exception,spring)