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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With