[英]Java Reflection: Class Annotations coming back null unexpectedly at runtime
我正在嘗試在運行時動態地向類添加注釋,如下所示:在運行時修改類定義的注釋字符串參數
但是,'annotations'字段將返回null。 實際上,根據調試器,除了“declaredFields”和“name”之外,類中的所有內容都返回null。 我正在使用Java 7。
這是我的代碼:
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);
看起來類字段annotations
是懶惰的,你首先需要強制它的初始化:
JsonIdentityInfo.class.getAnnotations();
然后繼續你的代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.