简体   繁体   English

如何使用CLASS的Java注释租赁策略

[英]How to use Java annotations rention policy for CLASS

I'm using annotations for generating documentation for an API that I'm publishing. 我正在使用注释为我正在发布的API生成文档。 I have it defined like this: 我把它定义如下:

@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface PropertyInfo {

    String description();

    String since() default "5.8";

    String link() default "";
}

Now this works fine when I process the classes using reflection. 现在,当我使用反射处理类时,这可以正常工作。 I can get the list of annotations on the method. 我可以获得该方法的注释列表。 The issue I have is that it only works if I instantiate a new instance of the object I'm processing. 我遇到的问题是它只有在我实例化我正在处理的对象的新实例时才有效。 I would prefer not to have to instantiate them to get the annotation. 我宁愿不必实例化它们来获取注释。 I tried RetentionPolicy.CLASS but it doesn't work. 我尝试了RetentionPolicy.CLASS,但它不起作用。

Any ideas? 有任何想法吗?

You don't need to instantiate an object, you just need the class. 您不需要实例化对象,只需要该类。 Here is an example: 这是一个例子:

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());
      }
    }
  }
}

Starting from Java5, classes are loaded lazily. 从Java5开始,类被懒惰地加载。

There are somes rules that determine if a class should be loaded. 有一些规则可以确定是否应该加载一个类。 The first active use of a class occurs when one of the following occurs: 当出现以下某种情况时,会发生类的第一次活动使用:

  • An instance of that class is created 创建该类的实例
  • An instance of one of its subclasses is initialized 初始化其子类之一的实例
  • One of its static fields is initialized 其中一个静态字段已初始化

So, in your case, merely referencing its name for reflection purposes is not enough to trigger its loading, and you cannot see the annotations. 因此,在您的情况下,仅仅为了反射而引用其名称不足以触发其加载,并且您无法看到注释。

You can get the annotations for a class using bean introspection: 您可以使用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.

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