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:

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
        }
    }
}   

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:

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) {
               String fieldName = field.getName();
               Field fieldOnResultIwant = 
                 resultIwant.getClass().getDeclaredField(fieldName);
               fieldOnResultIwant.setAccessible(true);
               // Honestly, I do not remember... Perhaps also will work:
               // field.set(resultIwant, value1);
               fieldOnResultIwant.set(resultIwant, value1);
            }
        }
        
    }  

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

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