标签:java java-8 method-reference functional-interface constructor-reference
我有一个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
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。