java – 默认方法中的自动构造函数匹配
作者:互联网
我有一个PersonFactory接口,如下所示:
@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;
}
}
我希望能够像这样实例化我的人:
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,java-8,method-reference,functional-interface,constructor-reference 来源: https://codeday.me/bug/20190519/1136117.html