Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two objects field by field and show the difference [closed]

Tags:

java

I want to compare two object i.e two database rows field by field. e.g. Object1[name="ABC", age=29, email="[email protected]"] and Object2[name="XYZ", age=29, email="[email protected]"]

suppose I want to compare these two object and I want output like this

[{
 "fieldName" : "email",
 "OldObjectValue" : "[email protected]",
 "NewObjectValue" : "[email protected]"
},
{
 "fieldName" : "name",
 "OldObjectValue" : "ABC",
 "NewObjectValue" : "XYZ"
}]

Here age is same so age field is not present in output.

If this is possible by doing generic method using reflection please provide some code. because I have not worked on reflection yet. Please help.

like image 315
Rohit K Avatar asked Dec 09 '22 01:12

Rohit K


1 Answers

According to your requirement you can do this as follow.

you can take two database rows to two objects. Eg: SampleObject

public class SampleObject {

private String name;
private int age;
private String email;   

public SampleObject(String name, int age, String email) {
    this.name = name;
    this.age = age;
    this.email = email;
}
.
.

I imagine your results will be an object too. Eg : ResultObject

public class ResultObject {

private String fieldName;
private String OldObjectValue;
private String NewObjectValue;
.
.

You can just define a compareField kind of method in SampleObject

public List<ResultObject> compareFields(SampleObject object) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{
    List<ResultObject> resultList = new ArrayList<ResultObject>();      
    Field[] fields = this.getClass().getDeclaredFields();

    for(Field field : fields){
        if(!field.get(this).equals(field.get(object))){
            ResultObject resultObject = new ResultObject();
            resultObject.setFieldName(field.getName());
            resultObject.setOldObjectValue(field.get(this).toString());
            resultObject.setNewObjectValue(field.get(object).toString());
            resultList.add(resultObject);
        }
    }
    return resultList;
}

Then you can make it work.

SampleObject object1 = new SampleObject("ABC", 29, "[email protected]");
    SampleObject object2 = new SampleObject("XYZ", 29, "[email protected]");

    List<ResultObject> resultList = object1.compareFields(object2);

Thanks

like image 165
isurujay Avatar answered Dec 11 '22 12:12

isurujay