The code is groovy but the answer can be in Java, no problem. I have a Person class with the following attributes:
class Persona(){
String nombre
String apellido
}
and I have a method that returns two person type objects, one with some attributes and the other with the rest. In my example it would be as if I had:
persona1 = "nombre : Juan"
persona2 = "apellido : Gónzalez"
And when "merging" it, what I want is that person1 be added the attributes that it does not have but that person2 does have. The output in this example would be:
persona1.merge(persona2)
persona1= "nombre : Juan, apellido : Gónzalez"
Is there a java or groovy api method that allows me to do this "merge" without writing each attribute by hand (iterating over all the attributes so I don't have to change the code if attributes are added or removed)?
If it doesn't exist, can you make a loop to iterate over the different attributes of a class to check the value of that attribute one by one?
I understand that you can do it via an if-else condition itself.
The same for the rest of the attributes.
EDIT: So that you don't have to do it for each attribute, or when you introduce new ones, I leave you this link where you can see how to go through all the attributes of a class: Loop Class Attributes
you can easily do it with org.apache.commons.beanutils BeanUtils.copyProperties(Object dest, Object orig);
You can also exclude null attributes or attributes that do not meet a certain condition. Ref http://www.avajava.com/tutorials/lessons/how-do-i-copy-properties-from-one-bean-to-another.html