Constructor References with Arguments
You'll learn how to use constructor references with functional interfaces that accept parameters, enabling you to create objects dynamically based on input values.
Core Concept
In the previous lesson, you saw constructor references for no-arg constructors using Supplier. But what if your constructor needs arguments? Java allows you to match constructor references to any functional interface whose abstract method signature matches the constructor's parameter list.
The key is parameter alignment: the functional interface's input types must match the constructor's parameter types, and the return type must be the class being constructed.
Common Functional Interfaces for Constructor References
Function<T, R> for Single-Argument Constructors
If a constructor takes one argument, use Function:
// Given: class Person { Person(String name) {...} }
Function<String, Person> personFactory = Person::new;
Person alice = personFactory.apply("Alice");
The Function takes a String (matching the constructor parameter) and returns a Person.
BiFunction<T, U, R> for Two-Argument Constructors
For constructors with two parameters:
// Given: class Person { Person(String name, int age) {...} }
BiFunction<String, Integer, Person> personFactory = Person::new;
Person bob = personFactory.apply("Bob", 30);
Custom Functional Interfaces
For three or more parameters, you'll need custom functional interfaces (or use existing ones if available):
@FunctionalInterface
interface TriFunction<T, U, V, R> {
R apply(T t, U u, V v);
}
// Given: class Person { Person(String name, int age, String city) {...} }
TriFunction<String, Integer, String, Person> factory = Person::new;
Key Takeaway: Constructor references work with any functional interface where the abstract method's parameters match the constructor's signature—use Function for one argument, BiFunction for two, or create custom interfaces for more.