简体   繁体   English

使用默认值在另一个自定义注释中定义自定义注释

[英]Define custom annotation within another custom annotation with default value

I am trying to declare custom annotation in following way: 我正在尝试通过以下方式声明自定义注释:

Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface InnerAnnotation {

}

Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface OuterAnnotation {
  public String default "";
  public InnerAnnotation innerAnnotation(); //here I wanted to do "public InnerAnnotation innerAnnotation() default {some default value}"
}

I wanted to use it in a way:
class first{
  @OuterAnnotation(value = "new") //wanted to declare something like this without need to define innerAnnotation
  public void func(){
  }
}

I wanted to assign some default value to inner annotation usage(so that I don't have to provide any mandatory value while using it), but some how I am not able to do that as compiler asks for compile time constant for this.Can any please suggest how to use inner annotation with any default value ? 我想为内部注释用法分配一些默认值(这样我就不必在使用时提供任何强制性值),但是由于编译器要求为此提供编译时间常数,因此我无法做到这一点。任何请建议如何使用具有任何默认值的内部注释?

The syntax for what you what is as follows: 您所用语法如下:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface OuterAnnotation {
    public String default "";
    public InnerAnnotation innerAnnotation() default @InnerAnnotation(); //this does the trick;  
}

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

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