Annotation member which holds other annotations?

前端 未结 5 819
耶瑟儿~
耶瑟儿~ 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:25

    Depending on the reason why you would want to specify other annotations there are multiple solutions:

    An array of instances of a single annotation type

    Probably not what you meant in your question, but if you want to specify multiple instances of a single annotation type it's certainly possible:

    public @interface Test {
        SomeAnnotation[] value();
    }
    

    An array of annotation types instead of instances

    If you do not need to specify any parameters on the individual annotations you can just user their class objects instead of instances.

    public @interface Test {
        Class[] value();
    }
    

    But an enum would of course also do the trick in most situations.

    Use multiple arrays

    If the set of possible annotation types you want to use is limited, you can create a separate parameter for each one.

    public @interface Test {
        SomeAnnotation[] somes() default { };
        ThisAnnotation[] thiss() default { };
        ThatAnnotation[] thats() default { };
    }
    

    Giving a default value to each member makes it possible to only specify arrays for the types you need.

提交回复
热议问题