vendredi 1 janvier 2021

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:

Test t1 = new Test();
t1.name = "Maria";
t1.age = 30;
t1.street = "somewhere";

Test t2 = new Test();
t2.name = "Maria";
t2.age = ;
t2.street = "here and here";

Test resultIwant = new Test();
t2.name = "Maria";
t2.age = 30;
t2.street = "here and here";

Code:

Test resultIwant = new Test(t2);

for(Field field : t1.getClass().getDeclaredFields()) {
    field.setAccessible(true);
    Object value1= field.get(t1);
    Object value2= field.get(t2);

    if ((value2 == null && value1 == null) || (value2 == value1))
        continue;
    else {
        if(value2 != null && value1 == null)
            continue;
        else if(value2 == null && value1 != null) {
            resultIwant.set???? = value1; <----------- this is my problem
        }
    }
}   




Aucun commentaire:

Enregistrer un commentaire