How to compare two objects and get the changed fields

GeekySelene picture GeekySelene · Mar 22, 2019 · Viewed 7.6k times · Source

In here im logging the changes that has been done to a particular Object record. So im comparing the old record and the updated record to log the updated fields as a String. Any idea how can I do this?

Answer

GeekySelene picture GeekySelene · Mar 22, 2019

Well i found a solution as below :

  private static List<String> getDifference(Object s1, Object s2) throws IllegalAccessException {
    List<String> values = new ArrayList<>();
    for (Field field : s1.getClass().getDeclaredFields()) {
        field.setAccessible(true);
        Object value1 = field.get(s1);
        Object value2 = field.get(s2);
        if (value1 != null && value2 != null) {
            if (!Objects.equals(value1, value2)) {
                values.add(String.valueOf(field.getName()+": "+value1+" -> "+value2));
            }
        }
    }
    return values;
}