How can I run a function before current function using annotations?
Is there any way for using an annotation for running a function before currently called function, something l开发者_开发知识库ike this:
public void doSomethingEarlier() {
}
@DoSomethingEarlier
public void doSomething() {
}
So I want to call doSomethin() function, and before executing this function I want to automatically run doSomethingEarlier() function.
You have a number of ways, which are a bit difficult to implement:
- use
Proxy
where you can parse the annotation on the target method and invoke a method with the same name - use AOP
The first approach is more straightforward. It would probably be better to have the annotation look something like:
@BeforeMethod("methodName")
In general, this is how AOP works on the low level.
See Spring Aspect Oriented Programming.
Java won't do this for you. Someone else: you or some library: has to see the annotation and adjust the call process.
Yes, you can use annotations for that. You have to create your own @DoSomethingEarlier
annotation (with run-time retention), and you have to code your own annotation processor processor. It is not an easy proposition, and you might want to look for other alternatives like AOP or dynamic proxies (which might not be easy either.)
This is easier...
public void doSomethingEarlier() {
}
public void doSomething() {
doSomethingEarlier();
}
精彩评论