3

I would like to copy the properties of an object to another, only if they are not null and exist in the target object. I know BeanUtils.copyProperties but it doesn't exactly suit the need.

What totally suit is the jquery.extend function. Is there an equivalent in the Java libraries/frameworks ? (or else I'll write my own...)

For example, the destination object is User, and the origin is UserSettings :

User                           UserSettings                     User
fisrtName="Rick"               firstName=null                  fisrtName="Rick"  
lastName="Dangerous"  extends  lastName="newLastName"  gives   lastName="newLastName"
nickName="RD"                                                  nickName="RD"


EDIT

Finally I wrote my own method, if anyone is interested see https://gist.github.com/1602045

8
  • what about .clone() method? you should be able to call obj.clone() and it will return cloned object Commented Jan 12, 2012 at 14:30
  • No because I have a target object with values I want to keep if the first object values are null. Commented Jan 12, 2012 at 14:33
  • 1
    To be honest this sounds like that your whole basic design of your program seems to be "off". Java and JavaScript are conceptually two completely different languages and an idea like jQuery's extend simply doesn't (or better "shouldn't") apply to Java. Can you give an example of the code and the classes you are using? And explain why you think yo need ´extend`. Commented Jan 12, 2012 at 14:36
  • Are those the examples objects (classes)? Why? Why not a Map? Commented Jan 12, 2012 at 14:54
  • They are objects, because UserSettings is an object populated by a html form jsonified, and User is a JPA entity. Commented Jan 12, 2012 at 14:55

2 Answers 2

1

Your code would still benefit from the beanutils

PropertyUtils.setSimpleProperty()

and

PropertyUtils.getSimpleProperty()

methods

Sign up to request clarification or add additional context in comments.

Comments

0

Maybe BeanUtilsBean.copyProperties(o1, o2)?

1 Comment

As I said it doesn't suit because null properties from origin object overrides ones of destination object. Null properties in origin object need to be skipped

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.