Reputation: 31
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.
Upvotes: 0
Views: 914
Reputation: 18825
There are two ways, both of them very complex, runtime and compile time solution:
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.
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.
Upvotes: 2