如何传递这个静态方法来代替实现接口的类?
我不确定这里发生了什么。这是一个接口:
public interface AppInit {
void create(Environment var1);
}
这是一些类的方法:
public static StandaloneModule create(AppInit appInit) {
return new StandaloneModule(appInit);
}
这是该方法的调用方式:
StandaloneModule.create(Main::configure)
但是该参数方法的签名是:
static void configure(final Environment environment) {
...
为什么要编译?
I'm not sure what's going on here. Here's an interface:
public interface AppInit {
void create(Environment var1);
}
Here's some class's method:
public static StandaloneModule create(AppInit appInit) {
return new StandaloneModule(appInit);
}
And here's how that method is being called:
StandaloneModule.create(Main::configure)
But that parameter method's signature is:
static void configure(final Environment environment) {
...
Why does this compile?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的接口是功能界面(即一种抽象方法)。特别是它是类型
环境
的消费者
。消费者进行争论,什么也没返回。因此,它只是消耗
参数,通常在其中应用某种类型。这是一个更常见的例子。打印
接口不必明确实现。编译器通过查找适当的接口并创建通常是匿名类的方法来解决此问题。
上述用方法参考调用。它也可以称为lambda。
这里
con.apply(“ Hello,World!”)
会将字符串传递给a
,并且将被打印。Your interface is a functional interface (i.e., one abstract method). In particular it is a
Consumer
of typeEnvironment
. A consumer takes an argument and returns nothing. So it justconsumes
the argument, usually applying some type to it. Here is a more common example.prints
The interface need not be explicitly implemented. The compiler takes care of that by finding the appropriate interface and creating what would normally be an anonymous class.
The above was called with a method reference. It could also be called as a lambda.
Here
con.apply("Hello, World!")
would pass the string to toa
and it would be printed.