Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging two objects in Java

I have two objects of same type.

Class A {
  String a;
  List b;
  int c;
}

A obj1 = new A();
A obj2 = new A();

obj1 => {a = "hello"; b = null; c = 10}
obj2 => {a = null; b = new ArrayList(); c = default value}

Can you please let me know what is the best way to combine this objects into single object?

obj3 = {a = "hello"; b = (same arraylist from obj2); c = 10}
like image 671
Ganesh Avatar asked Jul 06 '11 04:07

Ganesh


People also ask

How can we merge two objects?

To merge two objects in JavaScript, you can use the spread ... operator. The spread operator creates a new object with all the properties from the first and second object. If there's two properties with the same name, the property from the second object wins out.

How do you combine two objects in an array?

The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.

Can I add two objects in Java?

Is that possible? However, in Java there is no such thing as operator overloading. It would have to be written similar to i3 = i1. add(i2) (where add is a method that does the appropriate logic and creates the new object).


2 Answers

This works as long as you have POJOs with their own getters and setters. The method updates obj with non-null values from update. It calls setParameter() on obj with the return value of getParameter() on update:

public void merge(Object obj, Object update){
    if(!obj.getClass().isAssignableFrom(update.getClass())){
        return;
    }

    Method[] methods = obj.getClass().getMethods();

    for(Method fromMethod: methods){
        if(fromMethod.getDeclaringClass().equals(obj.getClass())
                && fromMethod.getName().startsWith("get")){

            String fromName = fromMethod.getName();
            String toName = fromName.replace("get", "set");

            try {
                Method toMetod = obj.getClass().getMethod(toName, fromMethod.getReturnType());
                Object value = fromMethod.invoke(update, (Object[])null);
                if(value != null){
                    toMetod.invoke(obj, value);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } 
        }
    }
}
like image 150
Alex Martín Jiménez Avatar answered Oct 14 '22 15:10

Alex Martín Jiménez


I am using Spring Framework. I was facing the same issue on a project.
To solve it i used the class BeanUtils and the above method,

public static void copyProperties(Object source, Object target)

This is an example,

public class Model1 {
    private String propertyA;
    private String propertyB;

    public Model1() {
        this.propertyA = "";
        this.propertyB = "";
    }

    public String getPropertyA() {
        return this.propertyA;
    }

    public void setPropertyA(String propertyA) {
        this.propertyA = propertyA;
    }

    public String getPropertyB() {
        return this.propertyB;
    }

    public void setPropertyB(String propertyB) {
        this.propertyB = propertyB;
    }
}

public class Model2 {
    private String propertyA;

    public Model2() {
        this.propertyA = "";
    }

    public String getPropertyA() {
        return this.propertyA;
    }

    public void setPropertyA(String propertyA) {
        this.propertyA = propertyA;
    }
}

public class JustATest {

    public void makeATest() {
        // Initalize one model per class.
        Model1 model1 = new Model1();
        model1.setPropertyA("1a");
        model1.setPropertyB("1b");

        Model2 model2 = new Model2();
        model2.setPropertyA("2a");

        // Merge properties using BeanUtils class.
        BeanUtils.copyProperties(model2, model1);

        // The output.
        System.out.println("Model1.propertyA:" + model1.getPropertyA(); //=> 2a
        System.out.println("Model1.propertyB:" + model1.getPropertyB(); //=> 1b
    }
}
like image 22
Georgios Syngouroglou Avatar answered Oct 14 '22 16:10

Georgios Syngouroglou