今天开发的时候在调用BeanUtils.copyProperties()的时候出现了异常,在网上找了一些这个方法的介绍,发现与我测试的结果不同,便记录一下我的测试过程与结果。
一.简介
首先简单介绍一下我用到这个方法的场景,有一个JavaBean的属性大部分都在另一个JavaBean中存在,现在需要把这个JavaBean中的同名的属性的值赋给另一个JavaBean对象,如果用get/set处理,需要大量的代码,用这个工具类的方法就能起到简化代码的作用。
这个方法有三个public修饰的重载方法,但其实都是调用的同一个方法copyProperties(Object source, Object target, Class editable, String[] ignoreProperties)
public static void copyProperties(Object source, Object target)
throws BeansException
{
copyProperties(source, target, null, null);
}
复制代码
public static void copyProperties(Object source, Object target, Class editable)
throws BeansException
{
copyProperties(source, target, null, null);
}
复制代码
public static void copyProperties(Object source, Object target, String[] ignoreProperties)
throws BeansException
{
copyProperties(source, target, null, null);
}
复制代码
二.原理
下面是此方法的源码
public 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(targ