使用BeanUitls提高对象拷贝效率

首先来创建两个bean
注:一定要有set/get方法,成员变量必须要同名

public class User1 {
    String name;
    String password;
    String phone;
/**省略get/set方法**/
}
public class User2 {
    String name;
    String password;
    String phone;
/**省略get/set方法**/
}

1.Spring的BeanUtils(简单易用)

org.springframework.beans.BeanUtils

BeanUtils.copyProperties(源对象,目标对象)
测试方法:

public static void main(String[] args){
        User1 user1=new User1();
        user1.setName("user1_name");
        user1.setPassword("user1_password");
        user1.setPhone("user1_phone");
        User2 user2=new User2();
        BeanUtils.copyProperties(user1,user2);
        System.out.println(user2.toString());
    }

执行结果:

User2(name=user1_name, password=user1_password, phone=user1_phone)
注:必须保证同名的两个成员变量类型相同,同名属性一个是包装类型,一个是非包装类型也是可以的

2.Apache的BeanUtils(拓展性强,相对复杂)

org.apache.commons.beanutils.BeanUtils

BeanUtils.copyProperties(目标对象,源对象)
需要引入依赖

    <dependency>
        <groupId>commons-beanutils</groupId>
        <artifactId>commons-beanutils</artifactId>
        <version>1.9.3</version>
    </dependency>

测试方法:

public static void main(String[] args) throws InvocationTargetException, IllegalAccessException {
        User1 user1=new User1();
        user1.setName("user1_name");
        user1.setPassword("user1_password");
        user1.setPhone("user1_phone");
        User2 user2=new User2();
        BeanUtils.copyProperties(user2,user1);
        System.out.println(user2.toString());
    }

执行结果:

User2(name=user1_name, password=user1_password, phone=user1_phone)

commons-beanutils则施加了很多的检验,包括类型的转换,甚至于还会检验对象所属的类的可访问性。BeanUtils能够顺利的完成对象属性值的复制,依赖于其对类型的识别。

原文参考https://www.jianshu.com/p/9b4f81005eb7

posted @ 2019-03-24 15:40  姜飞祥  阅读(722)  评论(0编辑  收藏  举报