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.

Share:
14,527
user219882
Author by

user219882

my about me is no longer blank

Updated on June 17, 2022

Comments

  • user219882
    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 the check() at the end? And if it is, can you provide some examples?

  • Kiran A B
    Kiran A B over 8 years
    Would you please share some example or link on how this can be achieved using AspectJ/Dynamic Proxy?
  • AlexR
    AlexR over 8 years
  • Spoke44
    Spoke44 almost 7 years
    Your 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
    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.