追蹤后臺字段的變化

需求:前臺開發(fā),需要后臺給數(shù)據(jù),一般開發(fā)后臺給的是Json格式的字符串,有后臺字段變化了 ,沒有來得及告訴我們,導致前臺bug,這個鍋我不背。為了第一時間知道后臺個的數(shù)據(jù)有沒有變化,所以就寫了一個方法判斷字段變化。在出現(xiàn)問題是第一時間解決。

實現(xiàn)原理:一般我們解析后臺數(shù)據(jù)都會生成一個JavaBean,利用反射將這個JavaBean 里字段名稱獲取出來,再和后臺數(shù)據(jù)進行比較。如果不一樣就輸出logr日志。是不是很簡單。

實現(xiàn)代碼

   //判斷后臺字段又沒有增加
    public static List getAddFiled(com.alibaba.fastjson.JSONObject json, Class<?> cls) {
        if (BuildConfig.DEBUG) {
            List<String> data = new ArrayList<>();
            try {
                LogUtils.d("最新字段總數(shù) = " + json.size());
                Field[] declaredFields = cls.getDeclaredFields();
                LogUtils.d("之前字段總數(shù) = " + declaredFields.length);
                Set<Map.Entry<String, Object>> entries = json.entrySet();
                for (Map.Entry<String, Object> entry : entries) {
                    for (int i = 0; i < declaredFields.length; i++) {
                        Annotation[] declaredAnnotations = declaredFields[i].getDeclaredAnnotations();
                        for (Annotation declaredAnnotation : declaredAnnotations) {
                            Class<? extends Annotation> aClass = declaredAnnotation.annotationType();
                            Field[] declaredFields1 = aClass.getDeclaredFields();
                            for (Field field : declaredFields1) {
                                String name = field.getName();
                                LogUtils.d(name);
                            }
                        }
                        if (entry.getKey().equals(declaredFields[i].getName())) {
                            break;
                        }
                        if (i == declaredFields.length - 1) {
                            data.add(entry.getKey());
                            LogUtils.d("新增加字段 = " + entry.getKey());
                        }
                    }
                }
            } catch (Exception e) {
                LogUtils.e(e);
            }

            return data;
        } else {
            return null;
        }

    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容