Search code examples
javaaop

Disable actual call of method by aspects


Is it possible to disable actuall method's call. What I would like to achieve is create aspect which will be called before my method and if some statement is true then not to call the main method at all.

Using pseudocode it would be something like this

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

Is it possible at all? Or maybe it is possible with something else not aspects?


Solution

  • Using @Around and ProceedingJoinPoint you should be able to do this. For example

      @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");
         }
      }
    

    I have set invokeMethod boolean to false here, but it should be the result of some computation which you would do to determine whether you want to execute a method or not. joinPoint.proceed does the actual invokation of the method.