java callback

What is callback?

A: The mail method as a parameter to a method for b, from b to call a.

Yes, remember these words on it.


Callback in JavaScript

The above conclusions JavaScript easier to understand because in JavaScript , the method is the object can be easily passed as a parameter to another method.

In JavaScript callback is used in the resource request


In java, the method is not an object, can not be passed to the method, how to understand?

Look at the following two pieces of code (from java programming ideas io)

//: io/DirList.java
// Display a directory listing using regular expressions.
//{Args: "D.*\.java"}
package org.qqwe.file;

import java.io.File;
import java.util.Arrays;
/**
 * @author 王阳明的徒弟
 */
public class DirList {
    public static void main(String[] args) {
        File path = new File(".");
        String[] list;
        if (args.length == 0) {
            list = path.list();
        } else {
            list = path.list(new DirFilter(args[0]));
        }
        Arrays.sort(list, String.CASE_INSENSITIVE_ORDER);
        for (String dirItem : list) {
            System.out.println(dirItem);
        }
    }
}

public class DirFilter implements FilenameFilter {

    private Pattern pattern;

    public DirFilter(String regex) {
        pattern = Pattern.compile(regex);
    }

    @Override
    public boolean accept(File dir, String name) {
        return pattern.matcher(name).matches();
    }
}

list of the first code with the reference method, accepts an object FilenameFilter Interface. The following class implements this interface, rewrite accept method.

This list will be executed when the method to execute the method accept incoming object, which is the callback, more specifically, it is a strategy model, the so-called strategy is to approach a target completion method. For example, I kill a person, murder is the goal, with large strokes kill, kill with a flat or a, this is the method that strategy. When writing I want to kill this approach, the strategy to stay out, as a parameter to get that policy mode.

in conclusion

In java, by passing an object to a method, make a call to the object's method b, this is a callback. Nb of nothing.


Published 16 original articles · won praise 8 · views 8500

Guess you like

Origin blog.csdn.net/qq_34637782/article/details/80910863