Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to "merge" two objects of the same class

Tags:

java

groovy

The code is groovy but the answer can be both, Groovy or Java. I have a Person class with this fields:

class Person(){
String name
String lasName
}

I have a method that returns two objects from the same class. One object with some fields and the other with the rest, in my example it would be like this:

person1 = "name : Jon"
person2 = "lastName : Snow"

What I need is to replace all the null fields of person1 with the person2 field if this is not null, in our example, the output would be:

person1.merge(person2)
person1= "name : Jon, lastName : Snow"

Is there any method on Java or Groovy to do something similar to this without writing all my fields(using some kind of loop)?

If there isn't any default method to use, how can I iterate through all the fields from a class?

like image 466
Blazerg Avatar asked Dec 19 '22 04:12

Blazerg


1 Answers

Just tested using reflection. The desired output is

merged person:Person{name=John, lastName=Snow}     



public static void testReflection() {
        Person p1 = new Person("John", null);
        Person p2 = new Person(null, "Snow");
        Person merged = (Person) mergePersons(p1, p2);
        System.out.println("merged person:" + merged);
}

public static Object mergePersons(Object obj1, Object obj2) throws Exception {
    Field[] allFields = obj1.getClass().getDeclaredFields();
    for (Field field : allFields) {
        if (Modifier.isPublic(field.getModifiers()) && field.isAccessible() && field.get(obj1) == null && field.get(obj2) != null) {
            field.set(obj1, field.get(obj2));
        }
    }
    return obj1;
}

mergePersons accepts two Objects.

Then it go through all fields and validate if the first object has a null value. If yes, then it verify if the second object is not nulled.

If this is true it assigns the value to the first Object.

Providing this solution you only access public data. If you want to access private data aswell, you need to remove the Modifier verification and set if accessible before like:

public static Object mergePersons(Object obj1, Object obj2) throws Exception {
    Field[] allFields = obj1.getClass().getDeclaredFields();
    for (Field field : allFields) {

        if (!field.isAccessible() && Modifier.isPrivate(field.getModifiers())) 
            field.setAccessible(true);
        if (field.get(obj1) == null && field.get(obj2) != null) {
            field.set(obj1, field.get(obj2));
        }
    }
    return obj1;
}
like image 81
Emanuel S Avatar answered Dec 20 '22 17:12

Emanuel S