두 자바 대상 비교

2529 단어 Java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class Comparer {

    private static final Logger logger = LoggerFactory.getLogger(Comparer.class);

    public static  Map compare(T obj1, T obj2)
            throws Exception {

        Map result = new HashMap();

        Field[] fs = obj1.getClass().getDeclaredFields();

        for (Field f : fs) {
            boolean comparedResult = false;
            Object v1 = null;
            Object v2 = null;
            try {
                f.setAccessible(true);
                v1 = f.get(obj1);
                v2 = f.get(obj2);
                String paramName = f.getName();
                logger.info("Param name1: {}.",paramName);
                if (v1 instanceof String || v1 instanceof Integer || v1 instanceof Double || v1 instanceof Float || v1 instanceof Boolean) {
                    comparedResult = v1.equals(v2);
                    result.put(paramName, String.valueOf(comparedResult));
                    logger.info("Param name: {}, result: {}, compared: {}.", paramName, v1, comparedResult);
                }else if (v1 instanceof List) {
                    List l1 = (List) v1;
                    List l2 = (List) v2;
                    if (l1.size() == l2.size()) {
                        for (int i = 0; i < l1.size(); i++) {
                            result.putAll(compare(l1.get(i), l2.get(i)));
                        }
                    }else {
                        comparedResult = false;
                        result.put(paramName, String.valueOf(comparedResult));
                        logger.warn("Param name: {}, result: {}, compared: {}.", paramName, v1, comparedResult);
                    }
                }else {
                    result.putAll(compare(v1, v2));
                }
            } catch (NullPointerException e) {
                String paramName = f.getName();
                if (v1 == v2) {
                    comparedResult = true;
                } else
                    comparedResult = false;
                result.put(paramName, String.valueOf(comparedResult));
                logger.warn("Param name: {}, result: {}, compared: {}.", paramName, v1, comparedResult);
            }
        }
        return result;
    }
}

좋은 웹페이지 즐겨찾기