代码之家  ›  专栏  ›  技术社区  ›  sproketboy

如何对类使用Java注释租用策略

  •  3
  • sproketboy  · 技术社区  · 15 年前

    我正在使用注释为我正在发布的API生成文档。我把它定义为:

    @Documented
    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface PropertyInfo {
    
        String description();
    
        String since() default "5.8";
    
        String link() default "";
    }
    

    3 回复  |  直到 15 年前
        1
  •  3
  •   True Soft    15 年前

    你不需要实例化一个对象,你只需要类。举个例子:

    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());
          }
        }
      }
    }
    
        2
  •  2
  •   Olivier Croisier    15 年前

    当发生下列情况之一时,类的第一次有效使用即发生:

    • 将创建该类的实例
    • 它的一个子类的实例被初始化
    • 其中一个静态字段已初始化

        3
  •  2
  •   Péter Török    15 年前

    您可以使用bean内省获取类的注释:

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