gpt4 book ai didi

java - 默认方法中的自动构造函数匹配

转载 作者:搜寻专家 更新时间:2023-10-31 20:00:59 25 4
gpt4 key购买 nike

我有一个 PersonFactory 接口(interface),如下所示:

@FunctionalInterface
public interface PersonFactory<P extends Person> {
P create(String firstname, String lastname);

// Return a person with no args
default P create() {
// Is there a way I could make this work?
}
}

Person 类:

public class Person {
public String firstname;
public String lastname;

public Person() {}

public Person(String firstname, String lastname) {
this.firstname = firstname;
this.lastname = lastname;
}
}

我希望能够像这样实例化我的 Person:

PersonFactory<Person> personFactory = Person::new;

Person p = personFactory.create(); // does not work
Person p = personFactory.create("firstname", "lastname"); // works

有没有办法让 Java 编译器通过匹配 PersonFactory.create() 的签名自动选择正确的构造函数?

最佳答案

一种方法是使用以下内容:

default P create() {
return create(null, null);
}

但我不确定这是否是您想要的。问题是您不能使方法引用引用 2 个不同的方法(或构造函数)。在这种情况下,您希望 Person::new 引用不带参数的构造函数带 2 个参数的构造函数,这是不可能的。

当你有:

@FunctionalInterface
public interface PersonFactory<P extends Person> {
P create(String firstname, String lastname);
}

像这样使用它

PersonFactory<Person> personFactory = Person::new;
Person p = personFactory.create("firstname", "lastname");

你必须意识到方法引用 Person::new 指的是采用 2 个参数的构造函数。下一行只是通过传递参数来调用它。

您还可以使用 lambda 表达式更明确地编写它:

PersonFactory<Person> personFactory = (s1, s2) -> new Person(s1, s2); // see, we have the 2 Strings here
Person p = personFactory.create("firstname", "lastname");

关于java - 默认方法中的自动构造函数匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34253956/

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