首页  >  文章  >  Java  >  AspectJ能否实现接口及其方法的注解继承?

AspectJ能否实现接口及其方法的注解继承?

Patricia Arquette
Patricia Arquette原创
2024-10-24 00:35:30313浏览

Can AspectJ Achieve Annotation Inheritance for Interfaces and Their Methods?

AspectJ 可以模拟接口及其方法的注解继承吗?

Java 注解继承受到限制,在接口、方法或方法上定义注解注释不是通过实现类、重写方法或使用带注释的注释的类继承的。此限制适用于在 JVM 约束下运行的 AspectJ。

解决方案:在特定情况下模拟注释继承

虽然注释继承的通用解决方案不可用,但有一种解决方法特定接口或方法存在:

<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>

实现:

  • ITD(类型间定义)手动将注释添加到接口并实现/覆盖类/方法。
  • 接口或方法上的实际注释可以删除。

结果:

控制台立即登录打印:

execution(de.scrum_master.app.Application())
execution(void de.scrum_master.app.Application.two())

替代解决方案:

方面可以嵌入到界面中,将实现合并到一个位置。将文件重命名为 .aj 以供编译器识别。

<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>

以上是AspectJ能否实现接口及其方法的注解继承?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn