tags:

views:

398

answers:

5

Is there a way in JAVA to call a callback function on every method of my class without having to explicitly do the call??

I don't want to do

public void foo()
{
   //some code
   callBackFunction()
}

I would like to do

public void foo()
{
   //some code
}

and then the class recognizes that it has to call the callBackFunction()

+1  A: 

You can use AOP for that - AspectJ for example, but be aware that there is a steep learning curve

Bozho
+8  A: 

Aspect-oriented programming is the simplest way to do this in a semi-global way. Use either AspectJ directly, or use an IOC container like Spring with supports aspects.

Essentially what you can do is define "pointcuts", which are a way of expressing where in the source code to do some other action. You can take that action (like calling callbackFunction()) either before, after, or instead of the existing method implementation.

Lots of other useful features in there, too, though be warned that it can lead to very hard-to-debug code if overused.

Benjamin Cox
+1 for "hard-to-debug." I would have written something more like "your name may be cursed by future generations...".
Bob Cross
LOL - great comment, Bob!
Benjamin Cox
+7  A: 

You can use reflection to inspect a class at runtime and wrap all of its methods, using what is called a "dynamic proxy" object. Check out the official Java documentation on reflection for an example (search that page for "DebugProxy", which actually implements a callback for entering and leaving each method).

David Winslow
+1  A: 

Several other folks already mentioned AOP and AspectJ. If you're not interested in using AspectJ, but still want some AOP functionality, Spring can help you implement it.

To make this work well, you should be coding against interfaces, so Spring can easily use Java Proxies to inject the AOP behavior. What happens is you get an alternate implementation of the interface, one that delegates calls to the "real" implementation, and adds a little extra work before and/or after the method call.

Frankly, you can do this without Proxies or Spring by just hand-writing a new implementation, e.g.

public void foo() {
    callbackFunction();
    this.delegate.foo();
}

where this.delegate is the "real" impl, but your client ends up calling the foo() method described above.

...
IFooBar y = new FooBar();   // implements IFooBar
IFooBar x = new FooBarProxy(y);   // also implements IFooBar, but with the callback and delegate
x.foo();  // calls y.foo() implicitly
...
saleemshafi
+2  A: 

same yourself some trouble and just call the method explicitly.

J Yu