views:

49

answers:

4

Is there any way for using an annotation for running a function before currently called function, something like 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.

+2  A: 

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.

Bozho
You'd have to define the annotation and write the proxy code, no?
bmargulies
yes (15 chars).
Bozho
A: 

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.

bmargulies
A: 

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.)

luis.espinal
A: 

This is easier...

public void doSomethingEarlier() {
}

public void doSomething() {
    doSomethingEarlier();
}
Chris Nava