Your question is interesting to me. I am looking a lot for your goals and find a small library. This library is located in google code and its name is jettison . This utility has a main class called Diff4J , which has a method with the diffs method, and it compares two objects and finds different ones.
Then I write codes for your purposes as follows:
fisrt define a Model Object named Bean :
public class Bean { private String name; private String family; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getFamily() { return family; } public void setFamily(String family) { this.family = family; } public Bean() { } public Bean(String name, String family ) { this.name = name; this.family = family; } }
Then coding the test class as follows:
public static void main(String[] args) throws IllegalAccessException, InvocationTargetException { Bean bean_1 = new Bean("Sara", "clooney"); Bean bean_2 = new Bean("Sally", "clooney"); Diff4J comparator = new Diff4J(); Collection<ChangeInfo> diffs = comparator.diff(bean_1, bean_2); Bean final_result = new Bean(); for(ChangeInfo c : diffs) { String filedName = c.getFieldName(); Object to_value = c.getTo(); Object from_value = c.getFrom(); BeanUtilsBean.getInstance().setProperty(final_result, filedName, to_value); } System.out.println(final_result); }
In this solution, if you run this code, see the following result:
Bean [family=null, name=Sally]
this result is your goal.
Note: In the last line of the loop statement, I used the BeanUtilBean from the Apache Commons Util for the Reflection fill object.
This utility has a problem, it does not support Deep Comparator (maybe I could not find it), and you should imitate this task.
To view this library, go to http://code.google.com/p/jettison/ .
I hope this answer helps you.