简体   繁体   English

Java注释属性限制

[英]Java Annotation Attribute limiting

I don't think this is possible but I wanted to throw the question out there just in case I am missing something. 我认为这是不可能的,但是我想把这个问题扔出去,以防万一我丢失了一些东西。 I have an annotation: 我有一个注释:

@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;
}

What I would like is a way to add an annotation to limit the Target for the attributes to either Type or Method. 我想要的是一种添加注释以将属性的Target限制为Type或Method的方法。

For example the attribute 'when' from above is limited to Method: 例如,上面的属性“何时”仅限于方法:

  /**
   * 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;

again I do not believe this is possible, but it would be nice to have. 再次,我不认为这是可能的,但是拥有它会很好。

No, there is no way to restrict that an annotation's attribute only be usable depending on the annotated target, at compile time. 不,没有方法可以限制注释的属性仅在编译时取决于注释的目标才可用。 You can always throw exceptions at runtime when processing the annotations. 处理注释时,您始终可以在运行时引发异常。

Otherwise, you'll have to define and use different annotation types. 否则,您将必须定义和使用不同的注释类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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