Vikdor
Vikdor

Reputation: 24134

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?

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.

Upvotes: 5

Views: 503

Answers (2)

skaffman
skaffman

Reputation: 403501

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.

Upvotes: 2

Bozho
Bozho

Reputation: 597114

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.

Upvotes: 1

Related Questions