Skip to content
Tags

,

JSR335: Method and Constructor References

August 14, 2013

A method reference is a way to refer to a method or constructor without invoking it. There are multiple forms of method/constructor references:

  • static methods – System::getProperty
  • instance methods – String::length or “abc”::length
  • superclass methods – super::toString
  • constructors – ArrayList::new or int[]::new

Method/Constructor references can be disambiguated by the functional interface targeted by the expression. The JDK already provides a package java.util.function filled with 43 functional interfaces that can and should be used for FunctionalInterface targets whenever possible. Getting familiar with all of these and their naming conventions is worth the small time investment.

NOTE: the JDK source code uses methods references heavily in java.util.stream functions such as map, collect, reduce, etc. The next major usage is in Comparator.comparing() static methods on the java.util.Comparator interface.

The examples below are provided from the JLS 8:

The examples here are some I wrote:

Advertisements

From → Java

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: