按方面禁用方法的实际调用

Disable actual call of method by aspects

是否可以禁用实际方法的调用。我想要实现的是创建方面,它将在我的方法之前调用,如果某些语句为真,则根本不调用主要方法。

使用伪代码会是这样的

public class MyClass {

  public void myMethod() {
     //implementation
  }
}

@Aspect
public class MyAspect {
  @Before("execution(* MyClass.myMethod(..))")
  public void doSth() {
    //do something here but if some statement is true then don't call myMethod
  }
}

有可能吗?或者也许可以用其他东西而不是方面?

使用 @AroundProceedingJoinPoint 你应该可以做到这一点。例如

  @Around("execution(* MyClass.myMethod())")
  public void doSth(ProceedingJoinPoint joinpoint) throws Throwable {

     boolean invokeMethod = false; //Should be result of some computation
     if(invokeMethod)
     {
         joinpoint.proceed();
     }
     else
     {
         System.out.println("My method was not invoked");
     }
  }

我在这里将 invokeMethod 布尔值设置为 false,但它应该是一些计算的结果,您可以通过这些计算来确定是否要执行某个方法。 joinPoint.proceed 执行方法的实际调用。