Skip to content
Advertisement

Compare objects and create a new one similar to one of them

I want to compare 2 objects and create a new one with the values of the second if its values are not null. Otherwise the values of the first one should be copied to the object created. My problem is that I don’t know how to set the value which I want to copy. I know that to get the name of the attribute I can use field.getName(), but how can I do the set of that attribute on the new object?

Example:

JavaScript

Code:

JavaScript

Advertisement

Answer

The Java Reflection API not only allows you to read but also to set a field value.

In your code you can try the following:

JavaScript

I posted a more complete, but related, answer here.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement