A method reference is just that: a reference to a method, no matter how many arguments the method actually has. A reference to a constructor is just a special case of method reference that references a constructor.
Suppose you have a Person
class:
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age age;
}
// getters, setters
}
Now also suppose you have a BiFunction<String, Integer, Person>
that maps name and age arguments to instances of the Person
class:
BiFunction<String, Integer, Person> personCreator =
(String name, Integer age) -> new Person(name, age);
Or, as the types of the parameter of a lambda expression are directly inferred by the compiler:
BiFunction<String, Integer, Person> personCreator = (name, age) -> new Person(name, age);
You can use this 2-arg function as follows:
Person joe = personCreator.apply("Joe", 25);
Now, did you notice that the type and order of the parameters in the (name, age)
lambda expression match those in the constructor? This means we might use a method reference instead:
BiFunction<String, Integer, Person> personCreator = Person::new;
And it will work, as expected:
Person jane = personCreator.apply("Jane", 23);
This is just to show you that the number of arguments doesn't matter when using method references. All that needs to match is the signature of the only one abstract method of a functional interface (in this case BiFunction.apply
) with the signature of the constructor.
If you want to further read about method references, go to the section about method references in the Java Tutorial.