org.apache.commons.beanutils复制属性忽略字段

huangapple go评论72阅读模式
英文:

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

huangapple
  • 本文由 发表于 2020年8月13日 20:26:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/63395166.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定