• 使用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

  • 相关阅读:
    statefulSet 原理理解
    kubernetes 集群机器重启后磁盘盘符变化
    去掉数据库外键约束
    kubernetes集群中对多个pod操作命令
    (转)怎么实时查看mysql当前连接数
    Got fatal error 1236 from master when reading data from binary log: 'Client requested master to start replication from impossible position
    phpfpm和nginx设置开机自动启动
    jquery ajax超时设置
    lumen中间件中设置响应header
    php支持多个地址跨域访问
  • 原文地址:https://www.cnblogs.com/smfx1314/p/10588461.html
Copyright © 2020-2023  润新知