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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19405421/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 16:53:04  来源:igfitidea点击:

What is a callback method in Java? (Term seems to be used loosely)

javaspring-mvccallback

提问by Horse Voice

I don't understand what a callback method is and I have heard people use that term very loosely. In the Java world, what is a callback method? If someone could provide some example code of a Java callback method with an explanation, it would be a great help in my Java learning journey.

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

Thank you in advance.

先感谢您。

采纳答案by Sotirios Delimanolis

A callback is a piece of code that you pass as an argument to some other code so that it executes it. Since Java doesn't yet support function pointers, they are implemented as Command objects. Something like

回调是一段代码,您将其作为参数传递给其他一些代码,以便它执行它。由于 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();
    }
}

A callback will usually hold reference to some state to actually be useful.

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

By making the callback implementation have all the dependencies to your code, you gain indirection between your code and the code that is executing the callback.

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

回答by Andrei I

A callback method in java is a method that gets called when an event (call it E) occurs. Usually you can implement that by passing an implementation of a certain interface to the system that is responsible for triggering the event E(see example 1).

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

Also in bigger and more complex systems you simply can annotate a method and the system will identify all annotated methods and will call them when the event occurs (see example 2). Of course the system defines what parameters the method should receive and other constraints.

同样在更大和更复杂的系统中,您只需注释一个方法,系统将识别所有注释的方法,并在事件发生时调用它们(参见示例 2)。当然,系统定义了方法应该接收哪些参数和其他约束。

Example 1:

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

Example 2:

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

回答by garvit94

In Simple Words...In plain English, a callback function is like a Worker who "calls back" to his Manager when he has completed a Task.

简单来说...简单来说,回调函数就像一个 Worker,当他完成一项任务时“回调”到他的经理。

How are they different from calling one function from another function taking some context from the calling function?It is true that you are calling a function from another function, but the key is that the callback is treated like an Object, so you can change which Function to call based on the state of the system (like the Strategy Design Pattern).

它们与从调用函数中获取一些上下文的另一个函数调用一个函数有何不同?的确,您正在从另一个函数调用一个函数,但关键是回调被视为一个对象,因此您可以根据系统的状态(如策略设计模式)更改要调用的函数。

How can their power be explained to a novice programmer? The power of callbacks can easily be seen in AJAX-style websites which need to pull data from a server. Downloading the new data may take some time. Without callbacks, your entire User Interface would "freeze up" while downloading the new data, or you would need to refresh the entire page rather than just part of it. With a callback, you can insert a "now loading" image and replace it with the new data once it is loaded.

如何向新手程序员解释他们的力量?在需要从服务器提取数据的 AJAX 风格的网站中,可以很容易地看到回调的威力。下载新数据可能需要一些时间。如果没有回调,您的整个用户界面将在下载新数据时“冻结”,或者您需要刷新整个页面而不仅仅是其中的一部分。通过回调,您可以插入“正在加载”图像,并在加载后将其替换为新数据。

Some code without a callback:

一些没有回调的代码:

     function grabAndFreeze() {
    showNowLoading(true);
    var jsondata = getData('http://yourserver.com/data/messages.json');
    /* User Interface 'freezes' while getting data */
    processData(jsondata);
    showNowLoading(false);
    do_other_stuff(); // not called until data fully downloaded
        }

      function processData(jsondata) { // do something with the data
    var count = jsondata.results ? jsondata.results.length : 0;
     $('#counter_messages').text(['Fetched', count, 'new items'].join(' '));
     $('#results_messages').html(jsondata.results || '(no new messages)');
       }

With Callback:Here is an example with a callback, using jQuery's getJSON:

带回调:这是一个带有回调的示例,使用 jQuery 的 getJSON:

    function processDataCB(jsondata) { // callback: update UI with results
   showNowLoading(false);
   var count = jsondata.results ? jsondata.results.length : 0;
   $('#counter_messages').text(['Fetched', count, 'new items'].join(' '));
   $('#results_messages').html(jsondata.results || '(no new messages)');
          }

`   `function grabAndGo() { // and don't freeze
    showNowLoading(true);
    $('#results_messages').html(now_loading_image);
    $.getJSON("http://yourserver.com/data/messages.json", processDataCB);
    /* Call processDataCB when data is downloaded, no frozen User Interface!                              
    do_other_stuff(); // called immediately

回答by Here_to_reason

In simple terms, callback mechanism refers to calling a function with another function as an argument. In languages like C,C++ this is done by passing function pointers as arguments but java doesn't have the concept of pointers. The workaround is interfaces. We pass reference to interfaces instead of pointers. Your understanding will be crystal clear after understanding the code below. To also show the real world applications, imagine purchasing a mouse and a mouse pad. The mouse pad price is fixed but mouse price differs by brand.

简单来说,回调机制是指以另一个函数为参数调用一个函数。在像 C、C++ 这样的语言中,这是通过将函数指针作为参数传递来完成的,但 java 没有指针的概念。解决方法是接口。我们传递对接口的引用而不是指针。理解下面的代码后,您的理解将一清二楚。为了展示真实世界的应用程序,想象一下购买鼠标和鼠标垫。鼠标垫价格是固定的,但鼠标价格因品牌而异。

interface mouse
{
    double mousePrice();
}
class BrandA implements mouse
{
    public double mousePrice()          //note that public access modifier is needed as all methods of interface are public are by default and when you override them
    //you cannot use any access modifier more restrictive
    {
        return 100;
    }

}

class BrandB implements mouse
{
    public double mousePrice()
    {
        return 200;
    }

}

class Simple
{
    static void total(mouse t)
    {
        double mousepad = 20;
        double mousep = t.mousePrice();
        System.out.println(mousepad + mousep);
    }
    public static void main(String args[])
    {
        mouse ob = new BrandA();        //upcasting. 
        total(ob);
    }
}

回答by VinKrish

@Sotirios Delimanolis answer is good but I wanted to give clear example which explains callbacks in a way how listeners works - following approach is greatly adopted by android library.

@Sotirios Delimanolis 的回答很好,但我想给出一个清晰的例子,它以侦听器的工作方式解释回调——android 库大量采用了以下方法。

class RemoteClass {

    private OnChangeListener mOnChangeListener;

    void makeSomeChanges() {
        /*
        .. do something here and call callback
        */
        mOnChangeListener.onChanged(this, 1);
    }

    public void setOnChangeListener(OnChangeListener listener) {
        mOnChangeListener = listener;
    }

    public interface OnChangeListener {
        public void onChanged(RemoteClass remoteClass, int test);
    }
}

There is a class built my someone, which goes by name RemoteClassand tells your class to reference the callback by passing implementation of OnChangeListenerinterface to setOnChangeListenermethod.

有一个类构建了我的某人,它通过名称RemoteClass告诉您的类通过将OnChangeListener接口的实现传递给setOnChangeListener方法来引用回调。

class Test {

    public static void main(String[] args) {    
        RemoteClass obj = new RemoteClass();
        obj.setOnChangeListener(demoChanged);
        obj.makeSomeChanges();
    }

    private static RemoteClass.OnChangeListener demoChanged = new RemoteClass.OnChangeListener() {
        @Override
        public void onChanged(RemoteClass remoteClass, int incoming) {
            switch (incoming) {
                case 1:
                    System.out.println("I will take appropriate action!");
                    break;
                default:
                    break;
            }
        }
    };
}

Now your class has finished doing its task and RemoteClassdoes its work and upon calling makeSomeChangeswhenever necessary results in onChangedmethod execution using mOnChangeListenerreference.

现在您的类已经完成了它的任务并RemoteClass完成了它的工作,并且在makeSomeChanges必要时调用会导致onChanged使用mOnChangeListener引用的方法执行。