简体   繁体   English

Java-通过参数传递方法

[英]Java - Passing a method through a parameter

I'm trying to create a method that allows me to make use of what I believe is called lambdas, to execute a method over a series of connections. 我正在尝试创建一种方法,该方法使我可以利用我认为的lambda来通过一系列连接执行一种方法。

Here's my code that I've come up with after some research, but it doesn't work: 经过一些研究,这是我提出的代码,但是它不起作用:

performGlobalAction(()->{
    // doSomething();
});

You'll also need to see the method I would assume: 您还需要查看我采用的方法:

private <T> void performGlobalAction(Callable<T> action) {
    for(int i = 0; i < connectionList.size(); i++) {
        connectionList.get(i).performAction(action);
    }
}

This provides the following error: 这提供了以下错误:

The method performAction(Callable<T>) in the type Connection is not
applicable for the arguments (() -> {})

The goal of this method is to allow myself to construct a method "on the go" without creating a void for it. 这种方法的目标是让我自己构造一个“随时随地”的方法,而不会为此造成空白。

Is this possible? 这可能吗? It seems like I've used plenty of statements that have done this before. 似乎我以前已经使用过很多声明。 It seems like this is actually exactly how lambdas statements work. 看来这实际上就是lambdas语句的工作方式。

The call method of the Callable interface returns a value of type T . Callable接口的call方法返回类型T的值。 Your lambda is simply shorthand for the call method, and likewise should return a T value. 您的lambda只是call方法的简写形式,同样应该返回T值。

Any interface that meets the requirements of a FunctionalInterface can be substituted by a lambda expression. 可以使用lambda表达式替换任何符合FunctionalInterface要求的接口。 Such an interface will have a single abstract method, one with no default implementation . 这样的接口将只有一个抽象方法,没有默认实现 For your question, the interface is Callable , and the abstract method is call . 对于您的问题,接口是Callable ,抽象方法是call The lambda expression then acts as the body of that abstract method in an anonymous implementation of that interface. 然后,lambda表达式在该接口的匿名实现中充当该抽象方法的主体。

Let's take as an example a method doStuff(Callable<Integer> stuff) . 让我们以doStuff(Callable<Integer> stuff)方法为例。 To satisfy this interface, you could give an anonymous class: 为了满足此接口,您可以提供一个匿名类:

doStuff(new Callable<Integer>(){
    public Integer call(){
        return 5;
    }
});

Or you could use a lambda: 或者您可以使用lambda:

doStuff( () -> {
    return 5;
} );

Or even more succinctly: 或更简洁地说:

doStuff( () -> 5 );

If your method doesn't have a return type, perhaps Runnable would be a better fit. 如果您的方法没有返回类型,那么Runnable可能会更合适。

See also: Lambda Expressions (Oracle) - 'Use Standard Functional Interfaces with Lambda Expressions' 另请参见: Lambda表达式(Oracle)-“在Lambda表达式中使用标准功能接口”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM