Hor*_*ice 31 java spring-mvc callback
我不明白回调方法是什么,我听说人们非常松散地使用这个术语.在java世界中,什么是回调方法?如果有人可以提供带有解释的java回调方法的示例代码,那么在我的java学习之旅中它会有很大的帮助吗?
先感谢您.
Sot*_*lis 39
回调是一段代码,您将其作为参数传递给其他代码,以便它执行它.由于Java尚不支持函数指针,因此它们实现为Command对象.就像是
public class Test {
public static void main(String[] args) throws Exception {
new Test().doWork(new Callback() { // implementing class
@Override
public void call() {
System.out.println("callback called");
}
});
}
public void doWork(Callback callback) {
System.out.println("doing work");
callback.call();
}
public interface Callback {
void call();
}
}
Run Code Online (Sandbox Code Playgroud)
回调通常会引用一些实际有用的状态.
通过使回调实现具有对代码的所有依赖性,您可以在代码和执行回调的代码之间获得间接.
java中的回调方法是在发生事件(调用它E)时调用的方法.通常,您可以通过将某个接口的实现传递给负责触发事件的系统来实现E(参见示例1).
此外,在更大,更复杂的系统中,您只需注释一个方法,系统就会识别所有带注释的方法,并在事件发生时调用它们(参见示例2).当然,系统定义了方法应该接收的参数和其他约束.
例1:
public interface Callback {
//parameters can be of any types, depending on the event defined
void callbackMethod(String aParameter);
}
public class CallbackImpl implements Callback {
void callbackMethod(String aParameter) {
//here you do your logic with the received paratemers
//System.out.println("Parameter received: " + aParameter);
}
}
//.... and then somewhere you have to tell the system to add the callback method
//e.g. systemInstance.addCallback(new CallbackImpl());
Run Code Online (Sandbox Code Playgroud)
例2:
//by annotating a method with this annotation, the system will know which method it should call.
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface CallbackAnnotation {}
public class AClass {
@CallbackAnnotation
void callbackMethod(String aParameter) {
//here you do your logic with the received paratemers
//System.out.println("Parameter received: " + aParameter);
}
}
//.... and then somewhere you have to tell the system to add the callback class
//and the system will create an instance of the callback class
//e.g. systemInstance.addCallbackClass(AClass.class);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
34232 次 |
| 最近记录: |