如何传递这个静态方法来代替实现接口的类?

发布于 2025-01-20 12:33:26 字数 466 浏览 4 评论 0原文

我不确定这里发生了什么。这是一个接口:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

手心的温暖 2025-01-27 12:33:26

您的接口是功能界面(即一种抽象方法)。特别是它是类型环境消费者。消费者进行争论,什么也没返回。因此,它只是消耗参数,通常在其中应用某种类型。这是一个更常见的例子。

interface Consumer {
      void apply(String arg);
}

public class ConsumerDemo  {
    public static void main(String [] args) {
        SomeMethod(System.out::println);
        
    }
    
    public static void SomeMethod(Consumer con) {
        con.apply("Hello, World!");
    }
}

打印

Hello, World!

接口不必明确实现。编译器通过查找适当的接口并创建通常是匿名类的方法来解决此问题。

上述用方法参考调用。它也可以称为lambda。

a -> System.out.println(a)

这里con.apply(“ Hello,World!”)会将字符串传递给a,并且将被打印。

Your interface is a functional interface (i.e., one abstract method). In particular it is a Consumer of type Environment. A consumer takes an argument and returns nothing. So it just consumes the argument, usually applying some type to it. Here is a more common example.

interface Consumer {
      void apply(String arg);
}

public class ConsumerDemo  {
    public static void main(String [] args) {
        SomeMethod(System.out::println);
        
    }
    
    public static void SomeMethod(Consumer con) {
        con.apply("Hello, World!");
    }
}

prints

Hello, World!

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.

a -> System.out.println(a)

Here con.apply("Hello, World!") would pass the string to to a and it would be printed.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文