@AspectJ 切入点,用于使用注释覆盖接口方法的方法 [英] @AspectJ pointcut for methods that override an interface method with an annotation

查看:31
本文介绍了@AspectJ 切入点,用于使用注释覆盖接口方法的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何编写适用于方法执行的切入点,该方法执行使用注释覆盖接口方法?例如:

How can I write an aspectj pointcut that applies to method executions which override an interface method with an annotation? For example:

interface A {
  @MyAnnotation void method();
}
class B implements A {
  void method();
}

切入点 execution(@MyAnnotation * *.*(..)) 仅在 B.method() 携带注释本身时才匹配.还有其他方法可以做到这一点吗?

The pointcut execution(@MyAnnotation * *.*(..)) does only match if B.method() carries the annotation itself. Is there another way to do this?

推荐答案

正如 Nicholas 所指出的,这在 AspectJ 中是不可能的.这是为什么不可能的更多证据(取自 http://www.eclipse.org/aspectj/doc/released/adk15notebook/annotations-pointcuts-and-advice.html 部分注解继承和切入点匹配):

As Nicholas pointed out, this is not possible in AspectJ. Here is more proof of why it is not possible (taken from http://www.eclipse.org/aspectj/doc/released/adk15notebook/annotations-pointcuts-and-advice.html section Annotation Inheritance and pointcut matching):

根据Java 5规范,非类型注解不会被继承,类型注解只有在有@Inherited元注解时才会被继承.对 c2.aMethod 的调用(在您的示例中为 b.method() )不匹配,因为修饰符(可见性修饰符、注释和 throws 子句)的连接点匹配基于连接点的主题(方法实际被调用).

According to the Java 5 specification, non-type annotations are not inherited, and annotations on types are only inherited if they have the @Inherited meta-annotation. The call to c2.aMethod (that would be b.method() in your example) is not matched because join point matching for modifiers (the visibility modifiers, annotations, and throws clause) is based on the subject of the join point (the method actually being called).

遇到了同样的问题,我写了一个小方法/库,可以让你为这些方法编写切入点.以下是您的示例的工作方式:

Having suffered from this same issue, I have written a small method/library that would allow you to write pointcuts for such methods. Here is how it would work for your example:

myAnnotationIsExecuted(): execution(public * *.*(..)) && 
             if(implementsAnnotation("@MyAnnotation()", thisJoinPoint));

myAnnotationIsExecuted(): execution(public * A+.*(..)) &&
             if(implementsAnnotation("@MyAnnotation()", thisJoinPoint));

方法 implementsAnnotation(String,JoinPoint) 来自库;一个基本方法,用于检查实现的方法是否包含指定的注解.

The method implementsAnnotation(String,JoinPoint) is coming from the library; a basic method that checks if the implemented methods contain the specified annotation.

可以在此处找到有关方法/库的更多信息.

这篇关于@AspectJ 切入点,用于使用注释覆盖接口方法的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆