Home >Java >javaTutorial >Why Doesn\'t AspectJ Intercept Annotated Classes and Methods Despite Interface and Method Annotations with @Marker?
Despite annotating an interface and methods with @Marker, an AspectJ aspect that expects to intercept annotated classes and methods doesn't trigger. Why does AspectJ not intercept them?
Annotation inheritance in Java has limitations. Annotations on interfaces, methods, or annotations are not inherited by implementing classes, overriding methods, or classes using annotated annotations. Only classes inherit annotations from superclasses if the annotation type in the superclass bears the @Inherited meta-annotation.
Since AspectJ works within the JVM's limitations, a workaround is needed to emulate annotation inheritance. A trick is to write an aspect that manually adds the annotation to the implementing classes and overriding methods:
<code class="java">public aspect MarkerAnnotationInheritor { // Implementing classes should inherit marker annotation declare @type: MyInterface+ : @Marker; // Overriding methods 'two' should inherit marker annotation declare @method : void MyInterface+.two() : @Marker; }</code>
This aspect adds the annotation to the interface and all implementing classes and methods, eliminating the need for literal annotations on those elements. With the aspect in place, the desired AspectJ interceptions will work as expected.
Alternatively, the aspect can be embedded directly into the interface:
<code class="java">public interface MyInterface { void one(); void two(); public static aspect MarkerAnnotationInheritor { declare @type: MyInterface+ : @Marker; declare @method : void MyInterface+.two() : @Marker; } }</code>
Renaming the file to MyInterface.aj allows AspectJ to recognize the aspect definition. Note that the modifiers in the aspect declaration can be omitted as nested members of interfaces are implicitly public static.
However, due to an AspectJ compiler issue, static should be explicitly declared for stability.
The above is the detailed content of Why Doesn\'t AspectJ Intercept Annotated Classes and Methods Despite Interface and Method Annotations with @Marker?. For more information, please follow other related articles on the PHP Chinese website!