什么是java中的回调方法?术语似乎松散地使用

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)

回调通常会引用一些实际有用的状态.

通过使回调实现具有对代码的所有依赖性,您可以在代码和执行回调的代码之间获得间接.

  • 这是一个很好的例子,我想添加以下内容:回调方法可以是任何类中的任何方法;对该类实例的引用在其他某个类中维护,并且当该其他类中发生某些事件时,它会从第一个类中调用该方法。使其成为与任何其他方法调用不同的回调的唯一方法是传递对对象的引用,以便该对象稍后调用其上的方法,通常是在某个事件上。 (4认同)

And*_*i I 6

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)