Reputation: 35276
This is my code for getting field values and annotation values, I placed the values into a map, however problem is there is a $this
that is in the map.
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);
}
}
}
}
}
Test output:
Key=id value=id1
Key=name value=Eli
Key=age value=25
Key=this$0 value=org.goo.AnnotationTest@7f5227
Upvotes: 0
Views: 963
Reputation: 400
You can use to get class variable and store in Map. Field[] fields = YourClassName.class.getFields();
Upvotes: 0
Reputation: 533500
The field this$0
is the reference to the outer class.
If you want to avoid this, make the class static
. IMHO you should make nested class static where possible, partly for performance, but mostly for clarity. If this is not an option, you can ignore that field explicitly.
BTW: If you create a field called this$0
it will use the field this$$0
or this$$$0
or this$$$$0
etc instead.
Upvotes: 1