将函数作为参数传递(Lambda)

3
我正在尝试理解Java 8的Lambda表达式。在这个例子中,我想解析一些文件。对于每个文件,我需要创建一个特定模板的新实例(对于同时传递的所有文件都相同)。
如果我理解正确的话,这就是Lambda表达式的好处。
请问有人可以用简单的术语解释如何将调用模板构造函数作为参数传递吗? (这样它可以是 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...
  }
}
1个回答

10
您可以使用 Supplier 和构造函数 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();
  }
}

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);
  }
}

Java 8 API在java.util.function包中提供了许多标准的函数接口,但通常不超过两个参数。您可以使用第三方n元函数接口(我为KludJe制作了some),也可以编写自己的函数接口。
自定义实现可能如下所示:
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);
}

哇,这个语法比我预期的还要更简洁!非常感谢! - not_a_number
我可以问另一个问题吗?如果模板的构造函数需要一个参数,比如文件本身(我不知道何时调用主方法),该怎么办?当然,我可以使用setter方法。但是是否有一种方法可以将参数传递给构造函数? - not_a_number
对于只有一个参数的构造函数,你可以使用 Function 来替换 Supplier。请参考java.util.function获取标准的函数接口,但如果需要的话,请编写自己的单抽象方法接口。 - McDowell
谢谢,麦克道尔。我仔细阅读了这篇文章,但是我觉得这个对我来说有点难度。看起来我只能使用setter方法了。 - not_a_number
我已经添加了几个例子。 - McDowell

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接