简体   繁体   中英

execute some code before and after of any method execution only by giving my custom annotation in java

I am trying to write a code for custom annotation. when I use this annotation on any method, then before execution and after execution of method some simple print msg should execute. I tried like this :

  import java.lang.annotation.*;

  @Retention(RetentionPolicy.RUNTIME)
  @interface DemoAnnotation {
  String value();
  String value1();
}

// Applying annotation
class CustomAnnotationExample {
@DemoAnnotation(value = "code is started!!!", value1= "code is completed!!!")
public void sayHello() {
    System.out.println("hello Annotation Example");
}
}

and in another main method I called it like :

    CustomAnnotationExample h=new CustomAnnotationExample();
    Method m=h.getClass().getMethod("sayHello");

    DemoAnnotation anno=m.getAnnotation(DemoAnnotation.class);

    System.out.println(anno.value());
    h.sayHello();
    System.out.println(anno.value1());

I want to print values from annotation without using System.out.println() in main method . when I just call sayHello() method . annotation values should get printed before and after execution of sayHello() method.

Please help me on this.

There are two ways, both of them very complex, runtime and compile time solution:

  1. The runtime solution relies on specific framework which is used to instantiate the application. The common way is to create wrapping proxies for the final object and do the stuff from the proxy before (or after) calling the original object method.

For spring for example the solution is to register BeanPostProcessor object which would intercept the instantiation of the bean and check whether some of the method contains the DemoAnnotation annotation. In case it does, it would create a proxy to that object and return the proxy as the real bean.

  1. Second solution is compile time solution and is based on annotation processors which can modify the java compiler behavior. You need to create and register annotation processor and after parsing the source file checking the annotations on the method and add the relevant code during the compilation time. There are many helpers, you can for example register on TreeScanner.visitMethod() method and invoke the TreeScanner from your annotation processor.

Generally the good example can be found in lombok which does similar things in terms of modifying the code during the compile time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM