让我稍微扩展一下您的示例代码,以便让您了解我的解决方案能做什么和不能做什么:
class A {
public void doA() {}
}
class B {
public void doB() {
new A().doA();
new C().doC();
}
}
class C {
public void doC() {
new A().doA();
}
}
class MyClass {
public static void main(String args[]) {
new A().doA(); // should not be captured
new B().doB(); // should be captured
}
}
如您所见,现在有一个新类C,我们现在有三个控制流:
MyClass.main -> A.doA
MyClass.main -> B.doB -> A.doA
MyClass.main -> B.doB -> C.doC -> A.doA
您想排除#1 并捕获#2,但是#3 呢?在这种情况下,a.doA 从B.doB 通过C.doC 调用间接。我的解决方案也捕捉到了这种间接情况。如果这对您来说很好,或者在您的代码库中没有发生,您可以使用我的解决方案。否则事情会变得有点复杂,你需要检查调用堆栈。如果您需要排除 #2,请告诉我,我会扩展我的答案,但我可以保证,解决方案看起来不像这个那么简单。
现在是方面:
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect
public class ControlFlowInterceptor {
@Before("execution(void A.doA()) && target(a) && cflow(execution(void B.doB()) && target(b))")
public void advice(JoinPoint thisJoinPoint, A a, B b) {
System.out.println(thisJoinPoint);
System.out.println(" " + a);
System.out.println(" " + b);
}
}
控制台输出如下所示:
execution(void A.doA())
A@7b19f779
B@65c66812
execution(void A.doA())
A@4df2868
B@65c66812
请注意,我们在两个输出中都有相同的 B 对象 ID,但是因为 C.doC 创建了一个新的 A 对象,所以我们有两个不同的 A 对象 ID。