[英]How to use Java annotations rention policy for CLASS
我正在使用注釋為我正在發布的API生成文檔。 我把它定義如下:
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface PropertyInfo {
String description();
String since() default "5.8";
String link() default "";
}
現在,當我使用反射處理類時,這可以正常工作。 我可以獲得該方法的注釋列表。 我遇到的問題是它只有在我實例化我正在處理的對象的新實例時才有效。 我寧願不必實例化它們來獲取注釋。 我嘗試了RetentionPolicy.CLASS,但它不起作用。
有任何想法嗎?
您不需要實例化對象,只需要該類。 這是一個例子:
public class Snippet {
@PropertyInfo(description = "test")
public void testMethod() {
}
public static void main(String[] args) {
for (Method m : Snippet.class.getMethods()) {
if (m.isAnnotationPresent(PropertyInfo.class)) {
System.out.println("The method "+m.getName()+
" has an annotation " + m.getAnnotation(PropertyInfo.class).description());
}
}
}
}
從Java5開始,類被懶惰地加載。
有一些規則可以確定是否應該加載一個類。 當出現以下某種情況時,會發生類的第一次活動使用:
因此,在您的情況下,僅僅為了反射而引用其名稱不足以觸發其加載,並且您無法看到注釋。
您可以使用bean introspection獲取類的注釋:
Class<?> mappedClass;
BeanInfo info = Introspector.getBeanInfo(mappedClass);
PropertyDescriptor[] descriptors = info.getPropertyDescriptors();
for (PropertyDescriptor descriptor : descriptors) {
Method readMethod = descriptor.getReadMethod();
PropertyInfo annotation = readMethod.getAnnotation(PropertyInfo.class);
if (annotation != null) {
System.out.println(annotation.description());
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.