java - Compare two objects field by field and show the difference -


i want compare 2 object i.e 2 database rows field field. e.g. object1[name="abc", age=29, email="abc@amail.com"] , object2[name="xyz", age=29, email="xyz@amail.com"]

suppose want compare these 2 object , want output this

[{  "fieldname" : "email",  "oldobjectvalue" : "abc@amail.com",  "newobjectvalue" : "xyz@amail.com" }, {  "fieldname" : "name",  "oldobjectvalue" : "abc",  "newobjectvalue" : "xyz" }] 

here age same age field not present in output.

if possible doing generic method using reflection please provide code. because have not worked on reflection yet. please help.

according requirement can follow.

you can take 2 database rows 2 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 results object too. eg : resultobject

public class resultobject {  private string fieldname; private string oldobjectvalue; private string newobjectvalue; . . 

you can define 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 can make work.

sampleobject object1 = new sampleobject("abc", 29, "abc@amail.com");     sampleobject object2 = new sampleobject("xyz", 29, "xyz@amail.com");      list<resultobject> resultlist = object1.comparefields(object2); 

thanks


Comments

Popular posts from this blog

python - ValueError: empty vocabulary; perhaps the documents only contain stop words -

ubuntu - collect2: fatal error: ld terminated with signal 9 [Killed] -

java - UnknownEntityTypeException: Unable to locate persister (Hibernate 5.0) -