Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

A constructor reference is a specialized form of a method reference in Java that provides a declarative shorthand for instantiating objects or arrays. It functions as a compact lambda expression, allowing a constructor to be treated as a first-class function and assigned to a compatible functional interface.

Syntax

The syntax utilizes the double-colon (::) operator appended to a class or array type, followed by the new keyword.
// Object instantiation
ClassName::new

// Array instantiation
Type[]::new

Resolution and Target Typing

Constructor references do not specify arguments directly. Instead, the Java compiler resolves the appropriate constructor through target typing. The compiler examines the signature of the single abstract method (SAM) within the target functional interface and matches its parameter types to an available constructor in the specified class.

1. No-Argument Constructor

If the functional interface method takes no arguments and returns an object, the compiler binds to the default or no-argument constructor.
// Lambda equivalent: () -> new StringBuilder()
Supplier<StringBuilder> supplier = StringBuilder::new; 

2. Parameterized Constructor

If the functional interface method accepts arguments, the compiler resolves to the overloaded constructor matching those exact parameter types.
// Lambda equivalent: (str) -> new String(str)
Function<String, String> function = String::new; 

// Lambda equivalent: (capacity, loadFactor) -> new HashMap<>(capacity, loadFactor)
BiFunction<Integer, Float, HashMap<String, String>> biFunction = HashMap::new;

3. Array Constructor

Array constructor references map to a functional interface whose method accepts a single int parameter (representing the array length) and returns an array of the specified type.
// Lambda equivalent: (length) -> new int[length]
IntFunction<int[]> arrayCreator = int[]::new;

Generic Type Inference

When dealing with generic classes, the compiler infers the type arguments from the context of the functional interface. However, explicit type witnesses can be provided between the class name and the :: operator if inference is insufficient.
// Inferred type arguments
Supplier<List<String>> inferred = ArrayList::new;

// Explicit type witness
Supplier<List<String>> explicit = ArrayList<String>::new;

Compilation Mechanics

At compile time, a constructor reference is translated into an invokedynamic instruction. The JVM dynamically generates the implementation of the functional interface, routing the SAM invocation directly to the invokespecial bytecode instruction associated with the resolved constructor, avoiding the creation of an anonymous inner class.
Master Java with Deep Grasping Methodology!Learn More