博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
使用BeanUitls提高对象拷贝效率
阅读量:3959 次
发布时间:2019-05-24

本文共 1537 字,大约阅读时间需要 5 分钟。

首先来创建两个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(目标对象,源对象)

需要引入依赖

commons-beanutils
commons-beanutils
1.9.3

测试方法:

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能够顺利的完成对象属性值的复制,依赖于其对类型的识别。

参考()

转载地址:http://jmazi.baihongyu.com/

你可能感兴趣的文章
杭电ACM——fatmouse's speed(DP)
查看>>
杭电ACM——毛毛虫(DP)
查看>>
杭电ACM——humble numbers(DP)
查看>>
杭电ACM——6467,简单数学题(思维)
查看>>
杭电ACM——天上掉馅饼(DP)
查看>>
杭电ACM——1086,You can Solve a Geometry Problem too(思维)
查看>>
杭电ACM——2057,A + B Again(思维)
查看>>
codeforces——1097B,Petr and a Combination Lock(搜索)
查看>>
杭电ACM——2064,汉诺塔III(递推)
查看>>
杭电ACM——2065,"红色病毒"问题(思维)
查看>>
北大ACM——2385,Apple Catching(DP)
查看>>
杭电AM——2072,单词数(暴力)
查看>>
杭电ACM——2073,无限的路(思维)
查看>>
杭电ACM——2069,Coin Change(DP)
查看>>
杭电ACM——2074,叠筐
查看>>
北大ACM——3616,Milking Time(DP)
查看>>
杭电ACM——2076,夹角有多大
查看>>
牛客练习赛43——B Tachibana Kanade Loves Probability(暴力,思维)
查看>>
牛客第十七届上海大学程序设计春季联赛——E CSL 的魔法(贪心)
查看>>
杭电ACM——1028,Ignatius and the Princess III(母函数)
查看>>