简体   繁体   English

传递函数作为参数(Lambda)

[英]Pass function as parameter (Lambda)

I'm trying to understand Java 8's Lambda expressions. 我正在尝试理解Java 8的Lambda表达式。 In the example, I want to parse a number of files. 在示例中,我想解析许多文件。 For each file, I need to create a new instance of the particular template (which is the same for all the files passed at a time). 对于每个文件,我需要创建特定模板的新实例(对于一次传递的所有文件,它是相同的)。

If I understood it right, that's what Lambda expressions are good for. 如果我理解正确,这就是Lambda表达式的优点。

Can anyone please explain to me in simple term how to pass the call to the template's constructor as a parameter? 任何人都可以用简单的术语向我解释如何将调用传递给模板的构造函数作为参数? (So that it could be new Template1() , new Template2() and so on). (这样它可能是new Template1()new Template2()等等。

import java.io.File;

public class Parser {

  public static void main(String[] args) {
    new Parser(new File[]{});
  }

  Parser(File[] files) {
    for (File f : files) {
      // How can I pass this as a parameter?
      Template t = new Template1();
    }
  }

  public class Template {
    // Code...
  }

  public class Template1 extends Template {
    // Code...
  }

  public class Template2 extends Template {
    // Code...
  }
}

You can use a Supplier and constructor reference : 您可以使用供应商和构造函数参考

public static void main(String[] args) {
  new Parser(new File[]{}, Template1::new);
}

Parser(File[] files, Supplier<Template> templateFactory) {
  for (File f : files) {
    Template t = templateFactory.get();
  }
}

The Function type could be used for a one-argument constructor like Template1(File) : Function类型可用于单参数构造函数,如Template1(File)

public static void main(String[] args) {
  new Parser(new File[]{}, Template1::new);
}

Parser(File[] files, Function<File, Template> templateFactory) {
  for (File f : files) {
    Template t = templateFactory.apply(f);
  }
}

The Java 8 API provides a number of standard functional interfaces in the java.util.function package though these typically don't extend beyond two arguments. Java 8 API在java.util.function包中提供了许多标准功能接口,尽管这些接口通常不会超出两个参数。 You can either use 3rd party nary functional interfaces (I made some for KludJe ) or write your own. 你可以使用第三方的nary功能接口(我为KludJe做了一些 )或自己编写。

A custom implementation might look like this: 自定义实现可能如下所示:

public static void main(String[] args) {
  new Parser(new File[]{}, Template1::new);
}

Parser(File[] files, TemplateFactory templateFactory) {
  for (File f : files) {
    Template t = templateFactory.createFrom(f);
  }
}

public static interface TemplateFactory {
  Template createFrom(File file);
}

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

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