【问题标题】:How to inherit custom annotation in Java?Java中如何继承自定义注解?
【发布时间】:2022-12-12 11:51:42
【问题描述】:

我想创建一个自定义注释,但我已经有一些更多的自定义注释,它们具有我需要的一些功能,所以我想将此功能放入一个单独的注释中,并在新注释的定义中重用它。如何使用 Java 中的现有注解定义新注解?

我一直在尝试注释现有注释的新注释的定义,但这不起作用

【问题讨论】:

    标签: java aop aspectj spring-aop aspect


    【解决方案1】:

    在 Java 中,您可以使用 @interface 关键字定义一个新的注释,后跟新注释的名称。要重用现有注释的功能,您可以使用@Inherited 和@Repeatable 注释。

    
    @Inherited
    @Repeatable(CustomAnnotations.class)
    @interface CustomAnnotation {
        // attributes and methods of the annotation go here
    }
    
    @Inherited
    @interface CustomAnnotations {
        CustomAnnotation[] value();
    }
    
    @CustomAnnotation
    class SomeClass {
        // class body goes here
    }
    

    在上面的示例中,CustomAnnotation 注释标有@Inherited 和@Repeatable 注释。这意味着注释可以被子类继承,并且可以多次应用于单个元素。 CustomAnnotations 注释用于在单个容器中保存多个 CustomAnnotation 注释。

    要在您的代码中使用 CustomAnnotation 注释,您可以使用 @ 符号将其应用于类或其他元素,后跟注释的名称。在上面的示例中,SomeClass 类标有 @CustomAnnotation 注释。

    如果您想在新注解中重用现有注解的功能,只需在新注解定义中扩展现有注解即可。

    
    @Inherited
    @interface ExistingAnnotation {
        // attributes and methods of the existing annotation go here
    }
    
    @Inherited
    @interface NewAnnotation extends ExistingAnnotation {
        // attributes and methods specific to the new annotation go here
    }
    

    在上面的示例中,NewAnnotation 注释扩展了 ExistingAnnotation 注释。这意味着它将具有现有注释的所有属性和方法,以及新注释中定义的任何其他属性和方法。

    要在您的代码中使用新注释,您可以像任何其他注释一样将其应用于类或其他元素。您还可以使用与前面示例相同的方式使用@Inherited 和@Repeatable 注释。

    【讨论】:

      猜你喜欢
      • 2012-12-18
      • 2020-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-13
      • 1970-01-01
      • 1970-01-01
      • 2011-07-29
      相关资源
      最近更新 更多