简体   繁体   中英

Java Reflection: Class Annotations coming back null unexpectedly at runtime

I'm trying to dynamically add an annotation to a class at runtime, as in this question: Modify a class definition's annotation string parameter at runtime

However, the 'annotations' field is coming back null. In fact, according to the debugger, everything on the class is coming back null except for "declaredFields" and "name". I'm using Java 7.

Here's my code:

Field field = Class.class.getDeclaredField("annotations");
field.setAccessible(true);
Map<Class<? extends Annotation>, Annotation> annotations = 
    (Map<Class<? extends Annotation>, Annotation>) 
        field.get(clazz);
annotations.put(JsonIdentityInfo.class, newAnnotation);

Seems that the class field annotations is lazily built and you first need to force its initialization:

JsonIdentityInfo.class.getAnnotations();

Then proceed with your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM