If an annotation is associated with a method while

2020-07-13 08:32发布

问题:

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 annotation is carried along with @Override annotation and if not, it should throw a compilation error?

Thanks.

回答1:

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.



回答2:

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.