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

This is about using annotations in Java. I associated the annotation with the method by declaring it in the interface. During implementation, how can I guarantee that the annotation is carried along with the @Override annotation, and if not, should it throw a compilation error?

Thanks.

+5
source share
2 answers

You can not.

You need to write code for this (either at the time the application loads, or using apt )

I had the same scenario and created my annotation:

@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, for example:

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

Imporant: , @Override (SOURCE), .

+1

, . , .

, Spring AnnotationsUtils , , JVM .

+1

All Articles