DEV Community

Erik Pischel
Erik Pischel

Posted on • Originally published at on-sw-integration.epischel.de on

Java method references recap

In the last post I reviewed Java lambda expressions.

They represent a concise syntax to implement functional interfaces.

Enter Java method references. They represent a concise syntax to implement functional interface using existing methods. Like with lambda expressions, referenced methods are not allowed to throw checked exceptions.

Syntax

It’s simply “class-or-instance name” “::” “method name”, like

Function<String, Integer> string2Int = Integer::valueOf;

Types of method references

Reference to a static method

Static methods are referenced using the class name like in the example above.

Reference to an instance method of a particular object

Methods of a particular object are referenced using the variable name of that object:

Map<Integer, String> aMap = new HashMap<>();
Function<Integer, String> getRef = aMap::get;
// call it
String s = getRef.apply(42);

Reference to an instance method of an arbitary object of a particular type

Instead of using an already existing object you can just state the class and a non-static method. Then the instance is an additional parameter. In the following example toURI is a method with no arguments that returns a String. The function of this method reference takes a File (the object) and returns a String:

Function<File, URI> file2Uri = File::toURI;

Reference to a constructor

Constructors are references using its type and “new”:

Function<String, StringBuffer> bufferFromString = StringBuffer::new;

Here the constructor of StringBuffer with String parameter is referenced. Return type is the type of the constructor, parameters of the function are the parameters of the constructors.

Top comments (0)