Shai Givati
Shai Givati

Reputation: 1156

Java annotation to determine whether the annotated method executes

In my methods, all my code is in an if block, testing certain condition.

public void myMethod() {
    if (/* some condition */) {
        //do something
    }
}

I would like to do this by annotation - meaning the annotation will execute some code that will "decide" whether or not the method should be invoked.

@AllowInvokeMethod(/* some parameters to decide */) 
public void myMethod() {
    //do something (if annotation allows invokation)
}

Is this possible?

Upvotes: 1

Views: 1155

Answers (2)

ekem chitsiga
ekem chitsiga

Reputation: 5753

You can use Spring AOP to create an ASpect to advise methods that are annotated your custom annotation

For example create an FilteredExecution annotation to be specified on your methods

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface FilteredExecution{
   Class<? extends ExecutionFilter> value();
}

ExecutionFilter is an interface to decide whether execution should occur

public interface ExecutionFilter{

   boolean sholudExecute();

}

Then the aspect

@Aspect
@Component
public class FilteredExceutionAspect{

  @Around("@annotion(filterAnnotation)")
  public void filter(ProceedingJoinPoint pjp , FilteredExecution filterAnnotation){
     boolean shouldExecute = checkShouldExecute(filterAnnotation);
     if(shouldExecute){
        pjp.proceed();
     }
  }

  private boolean checkShouldExecute(FilteredExecution filterAnnotation){
     //use reflection to invoke the ExecutionFilter specified on filterAnnotatoon
  }

You need to setup your context so that your beans with the custom annotation are auto proxied by using @EnableAspectjAutoProxy on your configuration class

Upvotes: 4

Irving Navarro Flores
Irving Navarro Flores

Reputation: 11

you can try this, documentation above metoh. this annotation is show when the method is invoke, and see the document of meothd

    /** 
      *   descripcion of the method
      * @param value , any value 
      */
    public void myMethod(String value) {
    //do something (if annotation allows invokation)
}

if you put this structure you can't see the documentation when you call some method,,

 //descripcion of the method
  public void myMethod(String value) {
        //do something (if annotation allows invokation)
    }

in my case, it works, i hope this works for you

Upvotes: 0

Related Questions