gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:46:41 27 4
gpt4 key购买 nike

我正在尝试理解 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...
}
}

最佳答案

您可以使用 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 中提供了许多标准功能接口(interface)包虽然这些通常不会超出两个参数。您可以使用 3rd 方 nary 功能接口(interface)(我为 some 制作了 KludJe )或编写您自己的接口(interface)。

自定义实现可能如下所示:

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

关于java - 将函数作为参数传递 (Lambda),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24911052/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com