Mybatis PropertyCopier 属性拷贝器的使用

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();
    }
  }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值