liveBook · Manning

Method reference

As explained in 100 Java Mistakes and How to Avoid Them

A method reference is a Java expression that refers to an existing method or constructor as an implementation of a functional interface.

A method reference is a concise Java expression that supplies an existing method or constructor where a functional interface is required. Its brevity can hide which overload is selected or whether the referenced method has the required semantics. section 2.13 section 2.15

Avoid these practical method-reference failures:

  • Check the target functional interface before binding an overloaded constructor or method; convert the reference to a lambda when the selected signature is unclear. section 2.13
  • Do not infer behavior from a method name alone: Integer::max fits Comparator's types but does not return the sign required for ordering. section 2.14
  • Use unit tests and heed static-analysis warnings, while recognizing that compilation alone does not establish correct behavior. section 2.14

A constructor reference that receives an unexpected argument

In contents.computeIfAbsent(fileName, StringBuilder::new), the mapping function receives the missing key. The reference can therefore select StringBuilder(String), producing content beginning with the filename. Use s -> new StringBuilder() when an empty builder is intended. section 2.13

IntBinaryOperator op = Integer::sum;  #1
IntBinaryOperator op = (a, b) -> Integer.sum(a, b);  #2

Compare a method reference with its equivalent lambda to expose the functional-interface parameters and the target method call. section 2.13

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains overload selection, functional-interface compatibility, semantic mismatch, testing, and lambda-based diagnosis, but not method-reference implementation internals.
Examples
Uses StringBuilder construction with computeIfAbsent and Integer::max supplied to List.sort as contrasting failure cases.
What it assumes
Assumes familiarity with Java functional interfaces, lambdas, overloaded methods, constructors, and collection APIs.
What you can do after
Diagnose method-reference mistakes by inspecting the target interface, expanding to a lambda, testing behavior, and applying an explicit comparator or constructor.
How it connects
Connects method references to lambda expressions, functional interfaces, overloaded constructors, computeIfAbsent, Comparator, and static analysis.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.