PropertyCopier使用,把user的属性拷贝到uesr1中。
public class PropertyCopierTest {
public static void main(String[] args) {
User user = new User();
user.setAge(18);
user.setName("tom");
User user1 = new User();
PropertyCopier.copyBeanProperties(User.class, user, user1);
System.out.println(user1.toString());
}
}
class User {
private int age;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"age=" + age +
", name='" + name + '\'' +
'}';
}
}
执行效果:
User{age=18, name='tom'}
PropertyCopier源码
package org.apache.ibatis.reflection.property;
import java.lang.reflect.Field;
import org.apache.ibatis.reflection.Reflector;
/**
* @author Clinton Begin
* 属性拷贝器
*/
public final class PropertyCopier {
private PropertyCopier() {
// Prevent Instantiation of Static Class
}
/**
* 完成对象的输出拷贝
* @param type 对象的类型
* @param sourceBean 提供属性值的对象
* @param destinationBean 要被写入新属性值的对象
*/
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 {
try {
field.set(destinationBean, field.get(sourceBean));
} catch (IllegalAccessException e) {
if (Reflector.canControlMemberAccessible()) {
field.setAccessible(true);
field.set(destinationBean, field.get(sourceBean));
} else {
throw e;
}
}
} catch (Exception e) {
// Nothing useful to do, will only fail on final fields, which will be ignored.
}
}
parent = parent.getSuperclass();
}
}
}