Java 如何将属性从一个 bean 复制到不同类中的另一个 bean?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19760590/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to copy properties from a bean to another bean in different class?
提问by user2683519
I have two java class with same properties names.How Can I copy all the properties to another bean filled with data.I don't want to use the traditional form to copy properties because I have a lot of properties.
我有两个属性名称相同的java类。如何将所有属性复制到另一个填充数据的bean。我不想使用传统形式复制属性,因为我有很多属性。
Thanks in advance.
提前致谢。
1 class
1班
@ManagedBean
@SessionScoped
public class UserManagedBean implements Serializable {
private static final long serialVersionUID = 1L;
private String userSessionId;
private String userId;
private String name;
private String adress;
......................
2 class
2班
public class UserBean {
private String userSessionId;
private String userId;
private String name;
....................
采纳答案by Mariusz Jamro
回答by sdanzig
If you use Apache's library, BeanUtils, you can do this easily:
如果您使用 Apache 的库 BeanUtils,您可以轻松地做到这一点:
http://commons.apache.org/proper/commons-beanutils/
http://commons.apache.org/proper/commons-beanutils/
In particular, look at copyProperties(Object, Object)
特别是看 copyProperties(Object, Object)
http://commons.apache.org/proper/commons-beanutils/apidocs/org/apache/commons/beanutils/BeanUtils.html#copyProperties(java.lang.Object, java.lang.Object)
http://commons.apache.org/proper/commons-beanutils/apidocs/org/apache/commons/beanutils/BeanUtils.html#copyProperties(java.lang.Object, java.lang.Object)
Copy property values from the origin bean to the destination bean for all cases where the property names are the same.
对于属性名称相同的所有情况,将属性值从源 bean 复制到目标 bean。
回答by Arvind
Use java reflection to set and get property values. There is spring bean property util which does the property value access. I would recommend to you java reflection.
使用 java 反射来设置和获取属性值。有 spring bean 属性 util 可以访问属性值。我会向你推荐java反射。
回答by Jasper Blues
Check out the Dozer Framework- its an object to object mapping framework. The idea is that:
查看Dozer 框架- 它是一个对象到对象映射框架。这个想法是:
- Usually it will map by convention.
- You can override this convention with a mapping file.
- 通常它会按惯例映射。
- 您可以使用映射文件覆盖此约定。
. . therefore mapping files are as compact as possible. Its useful for many cases, such as mapping a use-case specify service payload on to the reusable core model objects.
. . 因此映射文件尽可能紧凑。它在许多情况下很有用,例如将用例指定的服务有效负载映射到可重用的核心模型对象上。
When delivering the SpringSource training courses we used to point out this framework very often.
在提供 SpringSource 培训课程时,我们曾经经常指出这个框架。
Edit:
编辑:
These days try MapStruct.
这些天尝试MapStruct。