How to extend Java annotation?

前端 未结 6 1208
闹比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:48

    You can use annotation for annotation like this:

    @Target({ElementType.METHOD, ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Inherited
    @Documented
    @WithSecurityContext(factory = WithCustomUserSecurityContextFactory.class)
    public @interface WithCustomUser {
      String username() default "demo@demo.com";
      String password() default "demo";
      String[] authorities() default {Authority.USER};
    }
    

    And define exact state in its "child"

    @Target({ElementType.METHOD, ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Inherited
    @Documented
    @WithCustomUser(username = "admin@admin.com",
                    password = "admin",
                    authorities = {Authority.USER, Authority.ADMINISTRATOR})
    public @interface WithAdminUser {
    }
    

    In this case you have a some kind of "state" and access to the parent annotation fields via reflection/aspect.

提交回复
热议问题