Can AspectJ Emulate Annotation Inheritance for Interfaces and Their Methods?
Java annotation inheritance is restricted, with annotations defined on interfaces, methods, or annotations not inherited by implementing classes, overriding methods, or classes utilizing annotated annotations. This limitation applies to AspectJ, which operates within JVM constraints.
Solution: Emulating Annotation Inheritance in Specific Cases
While a general solution for annotation inheritance is unavailable, a workaround exists for specific interfaces or methods:
<code class="java">public aspect MarkerAnnotationInheritor { // Implementing classes inherit the marker annotation declare @type: MyInterface+ : @Marker; // Overriding 'two' method inherits the annotation declare @method : void MyInterface+.two() : @Marker; }</code>
Implementation:
Result:
The console log now prints:
execution(de.scrum_master.app.Application()) execution(void de.scrum_master.app.Application.two())
Alternative Solution:
The aspect can be embedded within the interface, consolidating the implementation in one location. Rename the file to
<code class="java">// MyInterface.aj public interface MyInterface { void one(); void two(); public static aspect MarkerAnnotationInheritor { declare @type: MyInterface+ : @Marker; declare @method : void MyInterface+.two() : @Marker; } }</code>
The above is the detailed content of Can AspectJ Achieve Annotation Inheritance for Interfaces and Their Methods?. For more information, please follow other related articles on the PHP Chinese website!