PropertyCopier属性复制器位于MyBatis中reflection包下子包property属性子包,其作用就是将一个对象的属性复制到另一个对象中。
源码如下:
public final class PropertyCopier {
private PropertyCopier() {
// Prevent Instantiation of Static Class
}
public static void copyBeanProperties(Class<?> type, Object sourceBean, Object destinationBean) {
Class<?> parent = type;
while (parent != null) {
// 获取所有字段属性
final Field[] fields = parent.getDeclaredFields();
for(Field field : fields) {
try {
// 设置访问权限
field.setAccessible(true);
field.set(destinationBean, field.get(sourceBean));
} catch (Exception e) {
// Nothing useful to do, will only fail on final fields, which will be ignored.
}
}
// 获取继承的字段属性
parent = parent.getSuperclass();
}
}
}
getDeclaredFields方法无法获取继承父类的字段属性。
禁止改动的类定义为final类型,私有化构造方法提供静态方法。
测试案例:
@SpringBootTest
public class TestPropertyCopier {
@Test
public void test1(){
User user1 = new User();
user1.setName("张三丰");
user1.setAge(100);
User user2 = new User();
System.out.println("复制前user2:"+user2.toString());
PropertyCopier.copyBeanProperties(User.class,user1,user2);
System.out.println("复制后user2:"+user2.toString());
}
}
测试结果: