Java中的回调方法是什么?(术语似乎使用得很松散)

2022-08-31 20:15:30

我不明白什么是回调方法,我听说人们非常松散地使用这个术语。在Java世界中,什么是回调方法?如果有人可以提供一些Java回调方法的示例代码并进行解释,那么这将对我的Java学习之旅有很大的帮助。


答案 1

回调是一段代码,作为参数传递给其他一些代码,以便它执行它。由于 Java 尚不支持函数指针,因此它们作为命令对象实现。类似的东西

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();
    }
}

回调通常会保存对某些状态的引用,以便实际有用。

通过使回调实现具有对代码的所有依赖关系,可以获得代码与执行回调的代码之间的间接关系。


答案 2

Java中的回调方法是在事件发生时调用(调用它)的方法。通常,您可以通过将某个接口的实现传递给负责触发事件的系统来实现这一点(请参阅示例 1)。EE

此外,在更大、更复杂的系统中,您只需对方法进行注释,系统将识别所有带注释的方法,并在事件发生时调用它们(请参阅示例 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());

示例 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);

推荐