Java callback methods
Can anybody help on how to implement callback methods using annotations in java ?
More detail -
Basically, I have a java method that returns nothing [void] but I wanted it to return the state of the object to the caller without changing the method signature using callback function. Hope 开发者_开发百科that helps.
Thank you!
Very simple.
In some class or interface somewhere you have a method that should be called: [access modifier] [return type] name([parameter list])...
for instance:
public void callback()
Then in some class you either override that method, or implement it, or something. Then in the code that does the callback you take an argument of the type of the class that has the callback method. For instance:
public interface Callback
{
public void callback();
}
public class Callbackee implements Callback {
public void callback()
{
System.out.println("Hey, you called.");`
}
static{
new Callbackee().doCallback();
}
}
public class CallBacker {
Callback call;
public void registerCallback(Callback call) {
this.call=call;
}
//then just do the callback whenever you want. You can also, of course, use collections to register more than one callback:
public void doCallback() {
call.callback();
}
}
If you want to see examples of callback methods in the Java API, look at MouseListener, MouseMotionListener, KeyListener and so forth. Usually you can register more than one callback of course.
Here is a nice tutorial about that:
http://slesinsky.org/brian/code/annotated_callback.html
Although I'm not sure if this is the thing you're thinking about.
You could wrap your Callback method in an http://download.oracle.com/javase/1.4.2/docs/api/java/awt/event/ActionListener.html class, then call ActionListener#actionPerformed(ActionEvent ev)
精彩评论