【问题标题】:Pass Variable From Nested Annotation In Java从 Java 中的嵌套注释传递变量
【发布时间】:2021-06-22 14:21:06
【问题描述】:

我想知道我可以从其他注释变量传递注释变量。让我用一个例子来解释一下:

主要注释:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Example2(value = Example1.other)
public @interface Example1
{
    String[] other() default {};
}

其他注释:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface Example2
{
    String[] value() default {};
}

在 Example1 注释中,我可以从 Example1 -> 其他属性传递 Example2 -> 值吗?

【问题讨论】:

    标签: java annotations


    【解决方案1】:

    简短的回答 - 不,你不能那样做。因为Example1.other属性值必须是常量。


    但你可以在@Example1 中声明常量值(final static String constant = "some constant value")并使用它:

    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Example2(Example1.constant)
    public @interface Example1 {
        String constant = "some constant value";
        String[] value() default "";
    }
    
    

    注意:注解中的所有变量默认都是final和static的。


    另外,您可以如下声明您的@Example2:

    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    @Inherited
    @Documented
    public @interface Example2 {
        Example1[] value();
    }
    

    并使用@Example1注解作为@Example2的元素:

    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Example2(@Example1({"some value", "some other value"}))
    public @interface Example1 {
        String[] value() default "";
    }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多