org.butor.utils.DiffUtils Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of butor-utils Show documentation
Show all versions of butor-utils Show documentation
This project is an utility module, contains utility functions for the other modules of the framework.
/**
* Copyright 2013-2017 butor.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.butor.utils;
import java.lang.reflect.Field;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import com.google.common.base.Throwables;
public class DiffUtils {
/**
* Returns an alphabetically sorted set of fields names that have differences in their value
* between two objects.
*
* It is very important that the field types of the object you are comparing override equals() and hashcode()
* otherwise the class might detect a difference where they are not
*
* @param o1 object
* @param o2 object
* @return set of string representing the difference between o1 and o2
*/
public static Set getDifferences(Object o1, Object o2) {
Set diffSet = new TreeSet();
Map mapObject1 = getFieldMap(o1);
Map mapObject2 = getFieldMap(o2);
populateDiffSet(diffSet, mapObject1, mapObject2);
populateDiffSet(diffSet, mapObject2, mapObject1);
return diffSet;
}
private static void populateDiffSet(Set diffSet,
Map map1, Map map2) {
for (Entry entry : map1.entrySet()) {
String fieldName = entry.getKey();
Object v1 = entry.getValue();
Object v2 = map2.get(fieldName);
if ((v1 != null && !v1.equals(v2)) || (v2 != null && !v2.equals(v1))) {
diffSet.add(fieldName);
}
}
}
private static Map getFieldMap(Object o1) {
Map mapObject1 = new TreeMap();
for (Field f : o1.getClass().getDeclaredFields()) {
f.setAccessible(true);
try {
mapObject1.put(f.getName(), f.get(o1));
} catch (Exception e) {
Throwables.propagate(e);
}
}
return mapObject1;
}
}