JAVA-如何将一个对象的属性复制到另一个具有相同属性的对象? [英] JAVA - How to copy attributes of an object to another object having the same attributes?

查看:1813
本文介绍了JAVA-如何将一个对象的属性复制到另一个具有相同属性的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个这样定义的对象A:

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

public class ObjectA {
    private Attribute a1;
    private Attribute a2;
    private Attribute a3;
}

由于某种原因,我需要创建仅包含第一个对象的第二个对象B对象A的两个属性:

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;
}

所以我的问题是:将对象A复制到的最佳方法是什么对象B?
我一直在一个个地复制getter和setter的属性,但是有些事情告诉我,必须有一种更好的方法!尤其是当对象将具有很多属性时,我必须编写一行代码来将它们全部复制到第二个对象B中。

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 ...

很多:)

编辑:另一个问题的可能重复提醒我:如何在Java中复制对象?

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

我的问题在某种程度上略有不同,即我正在处理2个仅共享相同属性但不完全相同的对象!

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);

或者如果您的目标类没有no-arg构造函数:

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 );

从文档(我强调):


执行Dozer映射后,结果将是目标对象的新实例,其中包含与源对象具有相同字段名称的所有字段的 。如果任何映射的属性具有不同的数据类型,则推土机映射引擎将自动执行数据类型转换。

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.

这篇关于JAVA-如何将一个对象的属性复制到另一个具有相同属性的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆