java Java回调方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4164654/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java callback methods
提问by jagamot
Can anybody help on how to implement callback methods using annotations in java ?
任何人都可以帮助如何使用 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.
基本上,我有一个不返回任何内容 [void] 的 java 方法,但我希望它将对象的状态返回给调用者,而无需使用回调函数更改方法签名。希望有帮助。
Thank you!
谢谢!
回答by Dude Dawg Homie
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.
如果您想查看 Java API 中回调方法的示例,请查看 MouseListener、MouseMotionListener、KeyListener 等。通常你当然可以注册多个回调。
回答by Marcin Cylke
Here is a nice tutorial about that:
这是一个很好的教程:
http://slesinsky.org/brian/code/annotated_callback.html
http://slesinsky.org/brian/code/annotated_callback.html
Although I'm not sure if this is the thing you're thinking about.
虽然我不确定这是否是你正在考虑的事情。
回答by Ahmed KRAIEM
You could wrap your Callback method in an http://download.oracle.com/javase/1.4.2/docs/api/java/awt/event/ActionListener.htmlclass, then call ActionListener#actionPerformed(ActionEvent ev)
您可以将回调方法包装在http://download.oracle.com/javase/1.4.2/docs/api/java/awt/event/ActionListener.html类中,然后调用 ActionListener#actionPerformed(ActionEvent ev)