Annotation which invokes a method
14,527
Solution 1
Yeah - it is possible. You need to instrument your code, typically with aspects (AOP). Check out this example if you want to see what it looks like.
Solution 2
It can be done with AOP. Take a look on AspectJ and Dynamic Proxy. Using dynamic proxy you can wrap your class with yet another piece of code that perform some things before and after actual method call.
Comments
-
user219882 almost 2 years
I'll start with a piece of code
class Clazz { public void doSomething() { ... check(); } public void doSomethingElse() { ... check(); } ... // etc., these methods look basically the same - they all call check() at the end }
Is it possible to annotate methods like
@Checked
which would cause to call thecheck()
at the end? And if it is, can you provide some examples? -
Kiran A B over 8 yearsWould you please share some example or link on how this can be achieved using AspectJ/Dynamic Proxy?
-
AlexR over 8 years@KiranAB, only for you docs.spring.io/spring/docs/current/spring-framework-reference/…
-
Spoke44 almost 7 yearsYour answer is not correct, your 'call your method' will be executed only when you reflect the class and not when the method is called. You can use Instrumentation for this purpose (github.com/jboss-javassist/javassist) or wrap your code in generated methods (github.com/square/javapoet for instance)
-
javamonkey79 almost 7 years@Spoke44 you're right. I think I must have misunderstood the question. I'm not sure why it was accepted and got more upvotes than the correct answer.