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

时间:2017-03-05 10:08:04

标签: java inheritance annotations aspectj

人们经常会问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不拦截它们?

1 个答案:

答案 0 :(得分:6)

这里的问题不是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(类型间定义)机制添加了他们回到接口加上所有实现/重写类/方法。

现在运行Application时的控制台日志说:

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