开发者

If an annotation is associated with a method while declaring it in an interface, can we force the presence of annotation in the implementation class?

开发者 https://www.devze.com 2022-12-16 10:10 出处:网络
This is regarding use of annotations in Java. I associated an annotation with a method while declaring it in the interface. While implementing, how can I ensure that the annota开发者_运维问答tion is c

This is regarding use of annotations in Java. I associated an annotation with a method while declaring it in the interface. While implementing, how can I ensure that the annota开发者_运维问答tion is carried along with @Override annotation and if not, it should throw a compilation error?

Thanks.


You can't enforce this in the compiler, no. It is the job of the tools which use those annotations to check all superclasses and interfaces when looking for annotations on a given class.

For example, Spring's AnnotationsUtils takes a class to examine for annotations, and crawls all over its inheritence tree looking for them, because the compiler and JVM does not do this for you.


You can't.

You need to write some code to do this (either on your applciation load time, or using apt)

I had the same scenario, and created an annotation of my own:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface DependsOn {
    Class<? extends Annotation>[] value();

    /**
     * Specifies whether all dependencies are required (default),
     * or any one of them suffices
     */
    boolean all() default true;
}

and applied it to other annotations, like:

@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = ElementType.TYPE)
@DependsOn(value={Override.class})
public @interface CustomAnnotation {
}

Imporant: have in mind that @Override has a compile-time (SOURCE) retention policy, i.e. it isn't available at run-time.

0

精彩评论

暂无评论...
验证码 换一张
取 消