How to compare 2 Java beans
Olivier Van de Velde
Technical Authority and Scrum Master EBP Web Apps at Siemens Mobility
Given the following function comparing 2 beans :
public static boolean compareBeans(Object bean1, Object bean2) {
First thing to do is to check if it is the same object and if they are not null :
if (bean1 == bean2) {
return true;
}
if (bean1 == null || bean2 == null) {
return false;
}
Remark that we don't need to check both are null because then they would be equal :
if (bean1 == null && bean2 == null) { return true; }
Once not null we can check if both beans belong to the same class :
if (bean1.getClass() != bean2.getClass()) {
return false;
}
For base types (primitive equivalent class + String) we can use the the equals function and no introspection for performance reasons.
Class<? extends Object> clazz = bean1.getClass();
if (clazz == String.class || clazz == Integer.class || clazz == Double.class || clazz == Float.class || clazz == Date.class) {
return bean1.equals(bean2);
}
Next only introspection is left, so let's first gather the information of the bean class :
BeanInfo beanInfo = null;
try {
beanInfo = Introspector.getBeanInfo(clazz);
} catch (IntrospectionException e) {
logger.log(Level.SEVERE, e.getMessage(), e);
return false;
}
Next we loop over all the properties, get the read method and invoke it on both beans. Both values are compared by recursively calling the current compareBeans function :
for (PropertyDescriptor prop : beanInfo.getPropertyDescriptors()) {
Method getter = prop.getReadMethod();
if (getter == null) {
continue;
}
Object value1 = null;
Object value2 = null;
try {
value1 = getter.invoke(bean1);
value2 = getter.invoke(bean2);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
logger.log(Level.SEVERE, e.getMessage(), e);
return false;
}
// compare the values as beans
if (!compareBeans(value1, value2)) {
return false;
}
}
return true;
Finally if all properties are equal true is returned.
LEAD ENGINEER || AWS CERTIFIED CLOUD PRACTIONER || SPRING BOOT MICROSERVICES
2 年Good Stuff. any library implements this and readily available to use?