英文:
org.apache.commons.beanutils copyProperties ignore fields
问题
我正在使用Java 7和org.apache.commons.beanutils
。
是否可以复制这些bean,但忽略特定的字段?
例如,我有以下代码:
import org.apache.commons.beanutils.BeanUtils;
BeanUtils.copyProperties(personDetails, person);
但希望不复制person
中名为password
的成员变量。
英文:
I am using Java 7 and org.apache.commons.beanutils
.
Is it possible to copy the beans, but ignore specific fields?
e.g. I have the following:
import org.apache.commons.beanutils.BeanUtils;
BeanUtils.copyProperties(personDetails, person);
But would like to not copy a member variable in person
called password
.
答案1
得分: 2
Apache BeanUtils没有提供忽略属性复制的选项。但是,您可以使用重载的方法,该方法可以复制单个属性,然后重复复制您想要复制的所有属性 -
public static void copyProperty(Object bean,
String name,
Object value)
throws IllegalAccessException,
InvocationTargetException
这将将指定的属性值复制到指定的目标bean中,并执行所需的任何类型转换。
如果您使用Spring的BeanUtil,它提供了一个忽略属性的选项 -
copyProperties(Object source, Object target, String... ignoreProperties)
将给定源bean的属性值复制到给定目标bean中,忽略给定的“ignoreProperties”。
英文:
Apapche beanutils doesn't give an option to ignore a property while copying.
However, you can use the overloaded method that can copy a single property and repeat for all the properties that you want to copy -
public static void copyProperty(Object bean,
String name,
Object value)
throws IllegalAccessException,
InvocationTargetException
This copies the specified property value to the specified destination bean, performing any type conversion that is required.
If you use spring's BeanUtil, it has an option to ignore properties -
copyProperties(Object source, Object target, String... ignoreProperties)
Copy the property values of the given source bean into the given target bean, ignoring the given "ignoreProperties".
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论