1

I want to achieve one functionality so that if we annotate a method with

@Skip(type = Execution.TRUE)

then the method will not be executed. I have defined own annotation like.

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Skip {
    Execution type() default Execution.FALSE;
}

and in the method definition i have defined like this way..

@Skip(type = Execution.TRUE)
    static void show(){
      System.ou.println("Hi");
    }

now if we call show() method from main() method.

This method will not be executed. How i can achieve it?

  • You would need to intercept every method call and determine if the target method is annotated. I don't think you can hook into the jvm to achieve this. – f1sh May 26 '17 at 11:18
  • Even if I don't get the need here .. your annoation is not in the runtime yet, but you will need to use reflection to get the annotation of the method. But why ? – AxelH May 26 '17 at 11:18
  • A way to do using aspectj https://stackoverflow.com/questions/42509158/custom-java-annotation-to-skip-the-method-execution – Optional May 26 '17 at 11:19

2 Answers2

2

Basically by creating your own java agent that will check at runtime if any method that is about to be invoked carries that property. And then skips execution.

Alternatively it might be possible to provide a piece of code that gets triggered at compile time. Maybe you could fine tune that to prevent method calls to be added into bytecode.

In any case - you are up to an advanced challenge. Maybe you should rather step back and outline the problem you intend to solve this way - so we can find a better solution to the underlying problem.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
-2

If you are writing your custom annotation you have to write the consumer as well. ie) You have to use java.lang.reflection mechanism to parse the class and invoke method based on the parameter which you have set. Java will provide the consumers only for the default annotations.

Shriram
  • 4,343
  • 8
  • 37
  • 64
  • And how would you implement that consumer? Without more details, this is not a useful answer. – f1sh May 26 '17 at 11:20