java对象相同属性复制,JAVA-如何将一个对象的属性复制到另一个具有相同属性的对象?...

在Java中,当你需要从一个对象复制属性到具有相同属性但不同类的对象时,通常的方法是通过getter和setter逐一设置。然而,当对象具有大量属性时,这种方法变得效率低下。一个更好的解决方案是使用第三方库如Dozer,它可以自动映射对象字段,大大简化了复制过程。只需一行代码,Dozer就能完成从ObjectA到ObjectB的属性复制,同时处理类型转换。
摘要由CSDN通过智能技术生成

Let's say we have an Object A defined like this:

public class ObjectA {

private Attribute a1;

private Attribute a2;

private Attribute a3;

}

For some reason, I need to create a second object B with only the first two attriutes of the Object A :

public class ObjectB {

private Attribute a1;

private Attribute a2;

}

So my question is: what is the best approach to copy an Object A to an Object B ?

I've been copying the attributes by getters and setters one by one but something tells me there must be a better way to do this ! Especially when the object will have a lot of attributes, I have to write lines and lines of code just to copy all of them to the second Object B ...

Thanks a lot :)

EDIT: I've been being alerted by a "possible duplicate of another question" : How do I copy an object in Java?

My question is slightly different in a way that I'm dealing with 2 different objects who just share the same attributes but not totally !

解决方案

To expand on my comment:

Using Dozer it can be as easy as:

Mapper mapper = new DozerBeanMapper();

ObjectA source = new ObjectA();

ObjectB target = mapper.map(source , ObjectB.class);

or if your target class doesn't have a no-arg constructor:

ObjectA source = new ObjectA();

ObjectB target = new ObjectB(/*args*/);

mapper.map(source, target );

From the Documentation (emphasis by me):

After performing the Dozer mapping, the result will be a new instance of the destination object that contains values for all fields that have the same field name as the source object. If any of the mapped attributes are of different data types, the Dozer mapping engine will automatically perform data type conversion.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值