Annotation member which holds other annotations?

前端 未结 5 809
耶瑟儿~
耶瑟儿~ 2020-12-29 11:55

I want to create a custom annotation (using Java) which would accept other annotations as parameter, something like:

public @interface ExclusiveOr {
    Anno         


        
5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-29 12:38

    I just ran into this exact problem, but (inspired by @ivan_ivanovich_ivanoff) I have discovered a way to specify a bundle of any combination of Annotations as an annotation member: use a prototype / template class.

    In this example I define a WhereOr (i.e. a "where clause" for my model annotation) which I need to contain arbitrary Spring meta-annotations (like @Qualifier meta-annotations).

    The minor (?) defect in this is the forced dereferencing that separates the implementation of the where clause with the concrete type that it describes.

    @Target({})
    @Retention(RetentionPolicy.RUNTIME)
    public @interface WhereOr {
        Class[] value() default {};
    }
    
    @Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    public @interface JsonModel {
        Class value();
        WhereOr where() default @WhereOr;
    }
    
    public class Prototypes {
        @Qualifier("myContext")
        @PreAuthorize("hasRole('ROLE_ADMINISTRATOR')")
        public static class ExampleAnd {
        }
    }
    
    @JsonModel(
            value = MusicLibrary.class,
            where = @WhereOr(Prototypes.ExampleAnd.class)
    )
    public interface JsonMusicLibrary {
        @JsonIgnore
        int getMajorVersion();
        // ...
    }
    

    I will programmatically extract the possible valid configurations from the "where clause" annotation. In this case I also use the prototypes class as a logical AND grouping and the array of classes as the logical OR.

提交回复
热议问题