打开网易新闻 查看精彩图片

日喀则市 · 雅鲁藏布江

1、使用org.springframework.beans.BeanUtils.copyProperties方法进行对象之间属性的赋值,避免通过get、set方法一个一个属性的赋值


* 对象属性拷贝

* 将源对象的属性拷贝到目标对象
*
* @param source 源对象
* @param target 目标对象
*/
public static void copyProperties(Object source, Object target) {
try {
BeanUtils.copyProperties(source, target);
} catch (BeansException e) {
LOGGER.error("BeanUtil property copy failed :BeansException", e);
} catch (Exception e) {
LOGGER.error("BeanUtil property copy failed:Exception", e);
}
}

2、List集合之间的对象属性赋值


* @param input 输入集合
* @param clzz 输出集合类型
* @param 输入集合类型
* @param 输出集合类型
* @return 返回集合
public static List convertList2List(List input, Class clzz) {
List output = Lists.newArrayList();
if (CollectionUtils.isNotEmpty(input)) {
for (E source : input) {
T target = BeanUtils.instantiate(clzz);
BeanUtil.copyProperties(source, target);
output.add(target);

return output;

比如有两个类,User和Employee,将存储Employee对象的List赋给存储User对象的List。,3000+ 道面试题在线刷,最新、最全 Java 面试题!

User类:

public class User {
private String name;
private Integer age;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}

@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}

Employee类:

public class Employee {
private String name;

private Integer age;
private String dept;

public Employee(String name, Integer age, String dept) {
this.name = name;
this.age = age;
this.dept = dept;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}

public String getDept() {
return dept;
}

public void setDept(String dept) {
this.dept = dept;
}

@Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", age=" + age +
", dept='" + dept + '\'' +
'}';
}
}

测试类:

@RunWith(PowerMockRunner.class)
public class TestUtil
@Test
public void test(){
Employee ee1=new Employee("A",21,"it");
Employee ee2=new Employee("B",23,"account");
User user=new User();
BeanUtil.copyProperties(ee1, user);
System.out.println(user);
System.out.println("-------------分割线--------------");
List output=new ArrayList<>();
List source= Arrays.asList(ee1,ee2);
output=BeanUtil.convertList2List(source,User.class);
for (User str:output) {
System.out.println(str);

打开网易新闻 查看精彩图片
作者:Terisadeng blog.csdn.net/dongyuxu342719/article/details/90242904

公众号“Java精选”所发表内容注明来源的,版权归原出处所有(无法查证版权的或者未注明出处的均来自网络,系转载,转载的目的在于传递更多信息,版权属于原作者。如有侵权,请联系,笔者会第一时间删除处理!

最近有很多人问,有没有读者交流群!加入方式很简单,公众号Java精选,回复“加群”,即可入群!

(微信小程序):3000+道面试题,包含Java基础、并发、JVM、线程、MQ系列、Redis、Spring系列、Elasticsearch、Docker、K8s、Flink、Spark、架构设计等,在线随时刷题!

特别推荐:专注分享最前沿的技术与资讯,为弯道超车做好准备及各种开源项目与高效率软件的公众号,「大咖笔记」,专注挖掘好东西,非常值得大家关注。点击下方公众号卡片关注

文章有帮助的话,点在看,转发吧!