需求:前臺開發(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;
}
}