Java Pass Method as Parameter

后端 未结 16 1002
滥情空心
滥情空心 2020-11-22 02:17

I am looking for a way to pass a method by reference. I understand that Java does not pass methods as parameters, however, I would like to get an alternative.

I\'ve

16条回答
  •  你的背包
    2020-11-22 02:49

    Since Java 8 there is a Function interface (docs), which has method

    R apply(T t);
    

    You can use it to pass functions as parameters to other functions. T is the input type of the function, R is the return type.

    In your example you need to pass a function that takes Component type as an input and returns nothing - Void. In this case Function is not the best choice, since there is no autoboxing of Void type. The interface you are looking for is called Consumer (docs) with method

    void accept(T t);
    

    It would look like this:

    public void setAllComponents(Component[] myComponentArray, Consumer myMethod) {
        for (Component leaf : myComponentArray) {
            if (leaf instanceof Container) { 
                Container node = (Container) leaf;
                setAllComponents(node.getComponents(), myMethod);
            } 
            myMethod.accept(leaf);
        } 
    }
    

    And you would call it using method references:

    setAllComponents(this.getComponents(), this::changeColor);
    setAllComponents(this.getComponents(), this::changeSize); 
    

    Assuming that you have defined changeColor() and changeSize() methods in the same class.


    If your method happens to accept more than one parameter, you can use BiFunction - T and U being types of input parameters and R being return type. There is also BiConsumer (two arguments, no return type). Unfortunately for 3 and more input parameters, you have to create an interface by yourself. For example:

    public interface Function4 {
    
        R apply(A a, B b, C c, D d);
    }
    

提交回复
热议问题