How to merge two objects in java

What you will learn here about java

  • How to merge two objects in java

Sometimes we come to situation where we want to add same type of objects together to add all fields of objects together. Here we will see how to merge two objects in java.

How to merge two objects in java

Please follow the following steps to know hpw to merge two ob in java.
1)First create simple java or maven project.

2)Now create a pojo class some fields which is shown below
java merge objects

3)Now will merge two same object to create a resultant object which is shown below.
We will merge two objects of same type
how to merge two objects java

The java code to merge two objects is given below
how to merge two objects in java

import java.lang.reflect.Field;
public class mainDriver {
    public static void main(String[] args) {
        Person person = new Person();
        Person newPerson = new Person();
        Person result= mergeObjects(person, newPerson);

    public static <T> T mergeObjects(T first, T second){
        Class<?> clas = first.getClass();
        Field[] fields = clas.getDeclaredFields();
        Object result = null;
        try {
            result = clas.getDeclaredConstructor().newInstance();
            for (Field field : fields) {
                Object value1 = field.get(first);
                Object value2 = field.get(second);
                Object value = (value1 != null) ? value1 : value2;
                field.set(result, value);
        } catch (Exception e) {
        return (T) result;

4)Once you run the above code you will see following kind of output which is shown below
merging objects in java

You may also like...