共分为两步
- 获取实体类的field字段。
public static Field[] getAllFields(Object object) {
Class<?> clazz = object.getClass();
List<Field> fieldList = new ArrayList<>();
while (clazz != null) {
fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields())));
clazz = clazz.getSuperclass();
}
Field[] fields = new Field[fieldList.size()];
fieldList.toArray(fields);
return fields;
}
- 通过getAnnotation方法获取拥有注解的字段。
JSONObject item = JSONObject.parseObject(json);
for (Field field : StringUtil.getAllFields(record)) {
if (field.getAnnotation(Hit.class) != null) { //判断字段是否包含Hit注解
String code = field.getAnnotation(Hit.class).hitCode(); //获取字段注解的hitCode值
String key = String.valueOf(item.get(field.getName()));
String textValue = translateDictValue(code, key);
}
}