這是用於獲取字段值和註釋值的代碼,我將這些值放入地圖中,但問題是地圖中存在$this
。獲取字段名稱和值並將其存儲在地圖中
Map doc = null;
String kind = null;
Class classObj = obj.getClass();
Annotation[] annotations = classObj.getAnnotations();
for (Annotation annotation : annotations) {
Entity entityAnnotation = (Entity)annotation;
kind = entityAnnotation.name();
if (entityAnnotation != null){
if (doc == null){
doc = new LinkedHashMap();
}
Field[] fields = classObj.getDeclaredFields();
for (Field field : fields){
annotations = field.getDeclaredAnnotations();
String value = null;
String fieldName = field.getName();
try {
boolean access = field.isAccessible();
field.setAccessible(true);
Object fieldValue = field.get(obj);
doc.put(fieldName, fieldValue);
field.setAccessible(access);
} catch (Exception e) {
e.printStackTrace();
}
// Process fields with annotation
for(Annotation fieldAnnotation : annotations){
if (annotation instanceof Id){
Id idAnnotation = (Id) fieldAnnotation;
log.info("Field name="+fieldName+" "+ value + " Annotation value: " + idAnnotation.value());
doc.put("_id", value);
}
}
}
}
}
測試輸出:
Key=id value=id1
Key=name value=Eli
Key=age value=25
Key=this$0 [email protected]
請問您可以縮進四個空格嗎? – 2012-11-14 08:57:12