Is there a Java library that can “diff” two Objects?

前端 未结 7 1032
长发绾君心
长发绾君心 2020-11-28 03:35

Is there a Java utility library that is analogous to the Unix program diff, but for Objects? I\'m looking for something that can compare two objects of the same type and ge

7条回答
  •  攒了一身酷
    2020-11-28 04:03

    Maybe this will help, depending on where you use this code, it could be useful or problematic. Tested this code.

        /**
     * @param firstInstance
     * @param secondInstance
     */
    protected static void findMatchingValues(SomeClass firstInstance,
            SomeClass secondInstance) {
        try {
            Class firstClass = firstInstance.getClass();
            Method[] firstClassMethodsArr = firstClass.getMethods();
    
            Class secondClass = firstInstance.getClass();
            Method[] secondClassMethodsArr = secondClass.getMethods();
    
    
            for (int i = 0; i < firstClassMethodsArr.length; i++) {
                Method firstClassMethod = firstClassMethodsArr[i];
                // target getter methods.
                if(firstClassMethod.getName().startsWith("get") 
                        && ((firstClassMethod.getParameterTypes()).length == 0)
                        && (!(firstClassMethod.getName().equals("getClass")))
                ){
    
                    Object firstValue;
                        firstValue = firstClassMethod.invoke(firstInstance, null);
    
                    logger.info(" Value "+firstValue+" Method "+firstClassMethod.getName());
    
                    for (int j = 0; j < secondClassMethodsArr.length; j++) {
                        Method secondClassMethod = secondClassMethodsArr[j];
                        if(secondClassMethod.getName().equals(firstClassMethod.getName())){
                            Object secondValue = secondClassMethod.invoke(secondInstance, null);
                            if(firstValue.equals(secondValue)){
                                logger.info(" Values do match! ");
                            }
                        }
                    }
                }
            }
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
    }
    

提交回复
热议问题