我正在寻找一种通过引用传递方法的方法。我知道Java不传递方法作为参数,但是,我想要一个替代方案。

我被告知接口是作为参数传递方法的替代方案,但我不理解接口如何通过引用充当方法。如果我理解正确的话,接口只是一组没有定义的抽象方法。我不想发送一个每次都需要定义的接口,因为几个不同的方法可以用相同的参数调用相同的方法。

我想要完成的是类似这样的事情:

public void setAllComponents(Component[] myComponentArray, Method myMethod) {
    for (Component leaf : myComponentArray) {
        if (leaf instanceof Container) { //recursive call if Container
            Container node = (Container) leaf;
            setAllComponents(node.getComponents(), myMethod);
        } //end if node
        myMethod(leaf);
    } //end looping through components
}

调用方法如下:

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

当前回答

编辑:在Java 8中,lambda表达式是一个很好的解决方案,正如其他答案所指出的那样。下面的答案是为Java 7和更早的版本编写的…


看一下命令模式。

// NOTE: code not tested, but I believe this is valid java...
public class CommandExample 
{
    public interface Command 
    {
        public void execute(Object data);
    }

    public class PrintCommand implements Command 
    {
        public void execute(Object data) 
        {
            System.out.println(data.toString());
        }    
    }

    public static void callCommand(Command command, Object data) 
    {
        command.execute(data);
    }

    public static void main(String... args) 
    {
        callCommand(new PrintCommand(), "hello world");
    }
}

编辑:正如Pete Kirkham所指出的,还有另一种使用访问者的方法。访问者方法稍微复杂一些——您的节点都需要使用acceptVisitor()方法来感知访问者——但如果您需要遍历一个更复杂的对象图,那么它就值得研究。

其他回答

关于如何使用java.util.function.Function作为简单方法的参数函数,我没有找到任何足够明确的示例。这里有一个简单的例子:

import java.util.function.Function;

public class Foo {

  private Foo(String parameter) {
    System.out.println("I'm a Foo " + parameter);
  }

  public static Foo method(final String parameter) {
    return new Foo(parameter);
  }

  private static Function parametrisedMethod(Function<String, Foo> function) {
    return function;
  }

  public static void main(String[] args) {
    parametrisedMethod(Foo::method).apply("from a method");
  }
}

基本上你有一个Foo对象和一个默认构造函数。将作为参数从类型为Function<String, Foo>的parameterisedmethod中调用的方法。

>表示该函数以String作为参数并返回Foo。 Foo::方法对应于类似x的lambda -> Foo. Method (x); parameterisedmethod (Foo::method)可以被看作x -> parameterisedmethod (Foo.method(x)) apply("from a method")基本上是执行parameterisedmethod (Foo。方法("来自一个方法"))

然后在输出中返回:

>> I'm a Foo from a method

示例应该按原样运行,然后您可以使用不同的类和接口从上面的答案中尝试更复杂的东西。

我不是java专家,但我可以这样解决你的问题:

@FunctionalInterface
public interface AutoCompleteCallable<T> {
  String call(T model) throws Exception;
}

我在我的特殊接口中定义了参数

public <T> void initialize(List<T> entries, AutoCompleteCallable getSearchText) {.......
//call here
String value = getSearchText.call(item);
...
}

最后,我实现getSearchText方法,同时调用初始化方法。

initialize(getMessageContactModelList(), new AutoCompleteCallable() {
          @Override
          public String call(Object model) throws Exception {
            return "custom string" + ((xxxModel)model.getTitle());
          }
        })

如果你不需要这些方法来返回一些东西,你可以让它们返回Runnable对象。

private Runnable methodName (final int arg) {
    return (new Runnable() {
        public void run() {
          // do stuff with arg
        }
    });
}

然后这样使用它:

private void otherMethodName (Runnable arg){
    arg.run();
}

使用观察者模式(有时也称为监听者模式):

interface ComponentDelegate {
    void doSomething(Component component);
}

public void setAllComponents(Component[] myComponentArray, ComponentDelegate delegate) {
    // ...
    delegate.doSomething(leaf);
}

setAllComponents(this.getComponents(), new ComponentDelegate() {
                                            void doSomething(Component component) {
                                                changeColor(component); // or do directly what you want
                                            }
                                       });

新的ComponentDelegate()……声明实现接口的匿名类型。

java 8起

Java 8以后,您可以使用lambda表达式提供函数接口(只有一个抽象方法的接口)的抽象方法的实现,并将其作为参数传递给方法。

@FunctionalInterface
interface ArithmeticFunction {
    public int calcualate(int a, int b);
}

public class Main {
    public static void main(String args[]) {
        ArithmeticFunction addition = (a, b) -> a + b;
        ArithmeticFunction subtraction = (a, b) -> a - b;

        int a = 20, b = 5;

        System.out.println(perform(addition, a, b));
        // or
        System.out.println(perform((x, y) -> x + y, a, b));

        System.out.println(perform(subtraction, a, b));
        // or
        System.out.println(perform((x, y) -> x - y, a, b));
    }

    static int perform(ArithmeticFunction function, int a, int b) {
        return function.calcualate(a, b);
    }
}

输出:

25
25
15
15

在线演示

从方法参考中了解更多信息。