简体   繁体   中英

Execute code using annotations before the method is executed

I want run some code before a method is executed at run-time and I want to achieve it using annotation. I have an annotation @SetValues

@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD })
public @interface SetValues
{}

I am new to annotations and have couple of questions

  1. How can I have some code being executed when this annotation is attached to a method
  2. How can i have the code associated with the annotation run before a method execution?

There are several ways this can be done:

  1. Aspect oriented programming was already mentioned, AspectJ is a standard here.
  2. You can write a piece of code yourself that does a similar thing. In this case you might want to wrap all (only some?) objects of interfaces which have those annotated methods in a proxy (have a look at java.lang.reflect.proxy ) which executes the code you want before the method itself is called (have a look at java.lang.reflect.InvocationHandler ). Combine this with Method.getDeclaredAnnotations() and you can probably build the thing you want.

But I'm not quite sure as to what you exactly it is you want. The name "SetValues" seems to imply that you want to change the value of certain fields (and maybe restore them after the execution of the method). You have to realise that the InvocationHandler can only do so much. It cannot and should not break encapsulation for example (at least not any more so than any other piece of code can do with the help of reflection). Another point to consider with such a feature is that it may interact very badly with concurrent execution of such methods when the InvocationHandler attempts to change values that both methods need.

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