tbruyelle
tbruyelle

Reputation: 13045

How could I augment object in Java with properties of another object?

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

Upvotes: 3

Views: 433

Answers (2)

Guillaume Serre
Guillaume Serre

Reputation: 301

Your code would still benefit from the beanutils

PropertyUtils.setSimpleProperty()

and

PropertyUtils.getSimpleProperty()

methods

Upvotes: 1

maerics
maerics

Reputation: 156434

Maybe BeanUtilsBean.copyProperties(o1, o2)?

Upvotes: 0

Related Questions