[英]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. 但是,'annotations'字段将返回null。 In fact, according to the debugger, everything on the class is coming back null except for "declaredFields" and "name". 实际上,根据调试器,除了“declaredFields”和“name”之外,类中的所有内容都返回null。 I'm using Java 7. 我正在使用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: 看起来类字段annotations
是懒惰的,你首先需要强制它的初始化:
JsonIdentityInfo.class.getAnnotations();
Then proceed with your code. 然后继续你的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.