5

我有一个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;
    }
}

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

PersonFactory<Person> personFactory = Person::new;

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

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

4

1 回答 1

5

一种方法是拥有以下内容:

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");
于 2015-12-13T17:30:26.887 回答