Percy

使用AspectJ模拟接口和方法的注释继承

java

人们经常会问诸如此类的AspectJ问题,因此我想在一个我以后可以轻松链接的地方回答它。

我有这个标记注释:

package de.scrum_master.app;

import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface Marker {}

现在,我注释这样的接口和/或方法:

package de.scrum_master.app;

@Marker
public interface MyInterface {
  void one();
  @Marker void two();
}

这是一个小的驱动程序应用程序,它也实现了该接口:

package de.scrum_master.app;

public class Application implements MyInterface {
  @Override
  public void one() {}

  @Override
  public void two() {}

  public static void main(String[] args) {
    Application application = new Application();
    application.one();
    application.two();
  }
}

现在,当我定义此方面时,我希望它会被触发

为每个构造函数执行带注释的类,并
每次执行带注释的方法。

package de.scrum_master.aspect;

import de.scrum_master.app.Marker;

public aspect MarkerAnnotationInterceptor {
  after() : execution((@Marker *).new(..)) && !within(MarkerAnnotationInterceptor) {
    System.out.println(thisJoinPoint);
  }

  after() : execution(@Marker * *(..)) && !within(MarkerAnnotationInterceptor) {
    System.out.println(thisJoinPoint);
  }
}

不幸的是,方面没有打印任何内容,就像类Application和方法two()没有任何@Marker注释一样。为什么AspectJ不截获它们?


阅读 393

收藏
2020-12-04

共1个答案

小编典典

这里的问题不是AspectJ,而是JVM。在Java中,

接口,
方法或
其他注释
永远不会被

实现类
覆盖方法或
使用带注释的注释的类。
注释继承仅在类到子类之间起作用,但仅当超类中使用的注释类型带有元注释时@Inherited,请参见JDK JavaDoc。

AspectJ是一种JVM语言,因此可以在JVM的限制内工作。对于此问题,没有通用的解决方案,但是对于要为其模拟注释继承的特定接口或方法,可以使用如下解决方法:

package de.scrum_master.aspect;

import de.scrum_master.app.Marker;
import de.scrum_master.app.MyInterface;

/**
 * It is a known JVM limitation that annotations are never inherited from interface
 * to implementing class or from method to overriding method, see explanation in
 * <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/annotation/Inherited.html">JDK API</a>.
 * <p>
 * Here is a little AspectJ trick which does it manually.
 *
 */
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;
}

请注意:有了这一方面,您可以从界面和带注释的方法中删除(文字)注释,因为AspectJ的ITD(类型间定义)机制将它们添加回接口以及所有实现/重写的类/方法。

现在,在运行Applicationsays的控制台日志中:

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

顺便说一句,您也可以将方面直接嵌入到界面中,以便将所有内容都放在一个位置。请小心重命名MyInterface.java为MyInterface.aj,以帮助AspectJ编译器认识到它必须在这里做一些工作。

package de.scrum_master.app;

public interface MyInterface {
  void one();
  void two();

  public static 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;
  }
}
2020-12-04