Java 注释属性限制

Java Annotation Attribute limiting

我不认为这是可能的,但我想把这个问题抛在那里以防万一我遗漏了什么。 我有一个注释:

@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Auditable {
  enum When{COMPLETE,ENTERING};
  /**
   * The list of attributes in this class to be audited
   * This is used at target level 'Type' only 
   * 
   * @return
   */
  String[] attributes() default {};

  /**
   * enum to dictate when to audit this message
   * This is used at target level 'method' only
   * 
   * @return
   */
  When when() default When.ENTERING;
}

我想要的是一种添加注释以将属性的目标限制为类型或方法的方法。

例如,上面的属性 'when' 仅限于方法:

  /**
   * enum to dictate when to audit this message
   * This is used at target level 'method' only
   * 
   * @return
   */
  @Target({ElementType.METHOD})
  When when() default When.ENTERING;

同样,我不相信这是可能的,但拥有它会很好。

不,没有办法限制注释的属性只能在编译时根据注释的目标使用。处理注释时,您始终可以在运行时抛出异常。

否则,您将不得不定义和使用不同的注释类型。