AspectJ:查找找到的JoinPoint的源方法代码/名称

时间:2020-02-12 14:37:00

标签: java aop aspectj aspectj-maven-plugin

我想检索调用特定方法的调用方法。
示例:
我考虑的方法:

public void methodA(int a, int b){...}

在测试方法中以及在程序本身中被调用

@Test
public void testMethodA(
... some code...
objectClassA.methodA(x,y);
)}

Class B {
...
 public void methodB(){
    objectClassA.methodA(x,y);
   }
}

我想要获取的是 testMethodA methodB 的内部或至少是签名

为此,我认为AspectJ可以为我提供帮助,因此我调查了一下并最终编写了此poincut
pointcut pcmethodA(): execution(* A.methodA(..) );

我的建议看起来像这样

before(): pcmethodA() {
        System.out.println("[AspectJ] Entering " + thisJoinPoint);
        System.out.println("[AspectJ] Signature " + thisJoinPoint.getSignature());
        System.out.println("[AspectJ] SourceLocation "+ thisJoinPoint.getSourceLocation());

但这返回

[AspectJ] Entering execution(void com.example.somePackage.A.methodA(int, int)
[AspectJ] Signature com.example.somePackage.A.methodA(int, int)
[AspectJ] SourceLocation A.java:25   /** Line number of the methodA in the file **/

这是我第一次使用AspectJ,是否有任何对象或方法可以检索我找到的连接点的调用方法? testMethodA 方法B

谢谢

1 个答案:

答案 0 :(得分:1)

让我首先使用一些示例类和驱动程序重新创建您的情况:

package de.scrum_master.app;

public class Foo {
  public void methodA(int a, int b) {
    System.out.println("methodA: " + a + ", " + b);
  }
}
package de.scrum_master.app;

public class DummyTest {
  public void testSomething() {
    new Foo().methodA(33, 44);
  }
}
package de.scrum_master.app;

public class Application {
  public void doSomething() {
    new Foo().methodA(11, 22);
  }

  public static void main(String[] args) {
    new Application().doSomething();
    new DummyTest().testSomething();
  }
}

现在就您的方面尝试将call()thisEnclosingJoinPointStaticPart组合使用:

package de.scrum_master.aspect;

import de.scrum_master.app.Foo;

public aspect MyAspect {
  pointcut pcmethodA() : call(* Foo.methodA(..));

  before() : pcmethodA() {
    System.out.println("[AspectJ] Executing: " + thisJoinPoint);
    System.out.println("[AspectJ] Called by: " + thisEnclosingJoinPointStaticPart);
  }
}

运行Application时的控制台日志:

[AspectJ] Executing: call(void de.scrum_master.app.Foo.methodA(int, int))
[AspectJ] Called by: execution(void de.scrum_master.app.Application.doSomething())
methodA: 11, 22
[AspectJ] Executing: call(void de.scrum_master.app.Foo.methodA(int, int))
[AspectJ] Called by: execution(void de.scrum_master.app.DummyTest.testSomething())
methodA: 33, 44

看到了吗?如果您只想确定调用方和被调用方,则无需处理堆栈跟踪。

相关问题