1

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.

2
  • Does this answer your question? how to ignore some fields in an object using BeanUtils.copyproperties in spring mvc Commented Aug 13, 2020 at 12:29
  • @RobertHarvey, thanks for the reply, but I am not using Spring, so have org.apache.commons.beanutils.BeanUtils and not BeanUtils from Spring. So the suggested solution will not work. If you marked this as close, please revert because your solution is not sutable. Commented Aug 13, 2020 at 12:31

1 Answer 1

2

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".
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.