Java Comparing Two objects Field by Field
Comparing two Java Objects using reflections.
package com.vivek.references;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
public class CompareFields {
private static final Logger logger = LoggerFactory.getLogger(CompareFields.class);
private CompareFields() {}
public static Map> compareFields(T source, T target) throws IllegalAccessException, InvocationTargetException {
Map> result = new HashMap<>();
if (source == null || target == null)
return null;
PropertyDescriptor[] propertyDescriptors;
try {
propertyDescriptors = Introspector.getBeanInfo(target.getClass()).getPropertyDescriptors();
} catch (IntrospectionException e) {
return null;
}
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
Method readMethod = propertyDescriptor.getReadMethod();
if (Objects.nonNull(readMethod)) {
if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
readMethod.setAccessible(true);
}
Object targetValue = readMethod.invoke(target);
Object sourceValue = readMethod.invoke(source);
if (targetValue == null && sourceValue == null) {
continue;
}
if (targetValue == null || !targetValue.equals(sourceValue)) {
result.put(propertyDescriptor.getName(), new Pair
Result : INFO [com.vivek.references.CompareFields][main] - Compare 1 - INFO [com.vivek.references.CompareFields][main] - Compare 2 - var4 => Pair [source=2, target=5] var1 => Pair [source=Var1, target=null]
Comments
Post a Comment