How to extend Java annotation?

前端 未结 6 1254
闹比i
闹比i 2020-12-09 01:08

In my project I use pre-defined annotation @With:

@With(Secure.class)
public class Test { //....

The source code of @Wit

6条回答
  •  余生分开走
    2020-12-09 01:38

    As piotrek pointed out, you cannot extend Annotations in the sense of inheritance. Still, you can create Annotations that aggregate others:

    @Retention(RetentionPolicy.RUNTIME)
    @Target({ElementType.TYPE})
    public @interface SuperAnnotation {
        String value();
    }
    
    @Retention(RetentionPolicy.RUNTIME)
    @Target({ElementType.TYPE})
    public @interface SubAnnotation {
        SuperAnnotation superAnnotation();
        String subValue();
    }
    

    Usage:

    @SubAnnotation(subValue = "...", superAnnotation = @SuperAnnotation(value = "superValue"))
    class someClass { ... }
    

提交回复
热议问题