Java is used to achieve a lambda expression callback method in JavaScript

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/milugloomy/article/details/83754113

background

In JavaScript, the callback function as a parameter to another function performed very common. For example, a simple loop array function, defined as follows:

function loopArray(arr, callback) {
  for (var i = 0; i < arr.length; i++) {
    callback(arr[i]);
  }
}

Here callback is the callback function for processing for each value in the array, call as follows:

var arr=[7,8,9];
forLoop(arr,function(node){
  console.log(node);
});

This will function as a parameter to another function, that is, the callback function. So how do you achieve this callback do in Java?

Callback method in Java

We still have to loop through the array, for example. First, the definition of a Interface, which is where we write the callback methods

public interface Callback {
    void callback(Integer num);
}

Then define classes and methods loop arrays

public class ArrayLooper {
    private Integer[] array;

    public ArrayLooper(Integer[] array) {
        this.array=array;
    }

    public void handle(Callback action){
        for(Integer num:array){
            action.callback(num);
        }
    }
}

Here handle incoming method parameters of action for the interface, it must implement this callback method Callback interface to handle when you call this method, thus achieving a callback.

Test classes are as follows:

public class TestMain {
    public static void main(String[] args) {
        Integer[] arr=new Integer[]{7,5,2};
        ArrayLooper arrayLooper=new ArrayLooper(arr);
        arrayLooper.handle(new Callback() {
            @Override
            public void callback(Integer num) {
                System.out.println(num);
            }
        });
    }
}

This is written before Java1.8, bloated code comparison, the Callback example of this interface and implements the callback method. After 1.8, using a lambda expression can be abbreviated as follows:

public class TestMain {
    public static void main(String[] args) {
        Integer[] arr=new Integer[]{7,5,2};
        ArrayLooper arrayLooper=new ArrayLooper(arr);
        arrayLooper.handle((num) -> {
            System.out.println(num);
        });
    }
}

It is not very convenient, and almost a JavaScript callback wording.

Guess you like

Origin blog.csdn.net/milugloomy/article/details/83754113