Home > Articles > Programming > Java

  • Print
  • + Share This
Like this article? We recommend

Method References

Java 8 introduces method references, which refer to methods or constructors without invoking them. These syntactic shortcuts create lambdas from existing methods or constructors. (Lambdas created from constructors are often referred to as constructor references, which I consider to be a subset of method references.)

Lambdas let us define anonymous methods and treat them as instances of functional interfaces. Method references let us accomplish the same thing, but with existing methods. Method references are similar to lambdas in that they require a target type. However, instead of providing method implementations, they refer to the methods of existing classes or objects.

There are four kinds of method references, which Table 1 describes.

Table 1: The Four Kinds of Method References

Kind of Method Reference

Syntax

Example

Reference to a static method

className::staticMethodName

String::valueOf

Reference to a bound non-static method

objectName::instanceMethodName

s::toString

Reference to an unbound non-static method

className::instanceMethodName

Object::toString

Reference to a constructor

className::new

String::new

A non-constructor method reference consists of a qualifier, followed by the :: symbol, followed by an identifier. The qualifier is either a type or an expression, and the identifier is the referenced method's name. The qualifier is a type for static methods, whereas the qualifier is a type or expression for non-static methods. If the qualifier is an expression, the expression is the object on which the method is invoked.

A constructor reference consists of a qualifier, followed by the :: symbol, followed by the keyword new. The qualifier is always a type, and the new keyword is the name of the referenced constructor. The qualifier type must support the creation of instances; for example, it cannot be the name of an abstract class or interface.

Before a non-static method can be invoked, an object on which to invoke this method is required. This target object is known as a receiver. The receiver can be provided as an expression (a bound non-static method) or a type (an unbound non-static method). I'll have more to say about receivers in these contexts later in this article.

References to Static Methods

A static method reference refers to a static method of the specified class. For example, in Listing 2, MethodRefDemo::doWork refers to the static doWork() method of the MethodRefDemo class.

Listing 2 MethodRefDemo.java (Version 1)

public class MethodRefDemo
{
   public static void main(String[] args)
   {
      new Thread(MethodRefDemo::doWork).start();
      new Thread(() -> doWork()).start();
      new Thread(new Runnable()
                 {
                    @Override
                    public void run()
                    {
                       doWork();
                    }
                 }).start();
   }

   static void doWork()
   {
      String name = Thread.currentThread().getName();
      for (int i = 0; i < 50; i++)
      {
         System.out.printf("%s: %d%n", name, i);
         try
         {
            Thread.sleep((int) (Math.random()*50));
         }
         catch (InterruptedException ie)
         {
         }
      }
   }
}

Listing 2 reveals three ways to pass a unit of work described by the doWork() method to a new Thread object whose associated thread is started:

  • Pass a method reference to the static doWork() method
  • Pass an equivalent lambda whose code block executes doWork()
  • Pass an instance of an anonymous class that implements Runnable and runs doWork()

Compile Listing 2 as follows:

javac MethodRefDemo

Run the MethodRefDemo application as follows:

java MethodRefDemo

You should observe output that's similar to the following prefix of the output:

Thread-0: 0
Thread-2: 0
Thread-1: 0
Thread-1: 1
Thread-2: 1
Thread-0: 1
Thread-0: 2
Thread-1: 2
Thread-2: 2
Thread-2: 3
Thread-1: 3

I've created a second example that employs String::format instead of the longer (String fmt, Object... args) -> String.format(fmt, args) lambda. Check out Listing 3.

Listing 3 MethodRefDemo.java (Version 2)

import java.util.Arrays;
import java.util.List;

@FunctionalInterface
interface Formatter
{
   String format(String fmtString, Object... arguments);
}

public class MethodRefDemo
{
   public static void main(String[] args)
   {
      List<String> names = Arrays.asList("Charlie Brown",
                                         "Snoopy",
                                         "Lucy",
                                         "Linus",
                                         "Woodstock");
      forEach(names, String::format);
      forEach(names, (fmt, arg) -> String.format(fmt, arg));
   }

   public static void forEach(List<String> list, Formatter formatter)
   {
      for (String item: list)
         System.out.print(formatter.format("%s%n", item));
      System.out.println();
   }
}

Listing 3 creates a list of strings and then invokes the forEach() static method twice with this list. The first invocation also passes a String::format method reference to String's static String format(String format, Object... args) method, and the second invocation also passes an equivalent lambda whose body invokes this method.

Compile Listing 3 (javac MethodRefDemo.java) and run this application (java MethodRefDemo). You should observe the following output:

Charlie Brown
Snoopy
Lucy
Linus
Woodstock

Charlie Brown
Snoopy
Lucy
Linus
Woodstock

References to Bound Non-Static Methods

A bound non-static method reference refers to a non-static method that's bound to a receiver. For example, System.out::printf is a non-static method reference that identifies the PrintStream printf(String format, Object args...) method of the java.io.PrintStream class. This method is bound to the System.out (standard output stream) object (the receiver) and will be invoked on this object. System.out::printf is equivalent to this lambda:

(String fmt, Object... args) -> System.out.printf(fmt, args)

Listing 4 demonstrates bound non-static method reference s::toString (from the earlier Table 1). It shows that this reference closes over s and invokes toString() on this instance.

Listing 4 MethodRefDemo.java (Version 3)

import java.util.function.Supplier;

public class MethodRefDemo
{
   public static void main(String[] args)
   {
      String s = "method references are cool";
      print(s::toString);
      print(() -> s.toString());
      print(new Supplier<String>()
      {
         @Override
         public String get()
         {
            return s.toString(); // closes over s
         }
      });
   }

   public static void print(Supplier<String> supplier)
   {
      System.out.println(supplier.get());
   }
}

Listing 4 assigns a string to String variable s and then invokes the static print() method with s::toString as the method's argument. This method reference equates to lambda () -> s.toString().

print() is defined to use the java.util.function.Supplier interface, which returns a supplier of results. In this case, the Supplier instance passed to print() has its get() method implemented to return s.toString().

The lambda receives no arguments and doesn't introduce s into the enclosing scope. Instead, this variable is accessed from the enclosing scope, and so the lambda behaves as a closure that closes over s.

Compile Listing 4 (javac MethodRefDemo.java) and run this application (java MethodRefDemo). You should observe the following output:

method references are cool
method references are cool
method references are cool

References to Unbound Non-Static Methods

An unbound non-static method reference refers to a non-static method that's not bound to a receiver. For example, String::trim is a non-static method reference that identifies the non-static String trim() method of the String class. Because a non-static method requires a receiver object, which in this example is a String object used to invoke trim() (via the method reference), the object is created by the virtual machine—trim() will be invoked on this object. String::trim specifies a method that takes a single String argument, which is the receiver object, and returns a String result. String::trim is equivalent to lambda (String s) -> { return s.trim(); }.

Listing 5 demonstrates unbound non-static method reference Object::toString (from the earlier Table 1). It shows that this reference requires a string to be passed to the method via the lambda and not via the enclosing scope.

Listing 5 MethodRefDemo.java (Version 4)

import java.util.function.Function;

public class MethodRefDemo
{
   public static void main(String[] args)
   {
      print(String::toString, "some string to be printed");
      print(s -> s.toString(), "some string to be printed");
      print(new Function<String, String>()
      {
         @Override
         public String apply(String s) // receives argument in parameter
         {                             // and doesn't need to close over
            return s.toString();       // it
         }
      }, "some string to be printed");
   }

   public static void print(Function<String, String> function, String value)
   {
      System.out.println(function.apply(value));
   }
}

Listing 5 invokes print() with a String::toString method reference and a string argument. Although the String part of String::toString looks like a class is being referenced, only an instance is referenced; the subsequent lambda makes this fact more obvious.

print() is defined to use the java.util.function.Function interface, which represents a function that accepts one argument and produces a result. In this case, the Function instance passed to print() has its apply() method implemented to return s.toString().

The anonymous class in the third print() method call shows that the lambda receives an argument; it doesn't close over s and therefore is not a closure.

Compile Listing 5 (javac MethodRefDemo.java) and run this application (java MethodRefDemo). You should observe the following output:

some string to be printed
some string to be printed
some string to be printed

References to Constructors

A constructor reference refers to a constructor without instantiating the named class. You can create and pass (to methods) references to existing constructors (as method arguments), or you can assign these references to target types.

In a constructor reference expression, you don't specify the exact constructor. Instead, you simply write new. When a class declares multiple constructors, the compiler will check the type of the functional interface with all of the constructors and choose the best match.

Table 2 presents a few examples of constructor references and their equivalent lambda expressions.

Table 2: Examples of Constructor References and Their Lambda Equivalents

Constructor Reference

Lambda Equivalent

Integer::new

(int value) -> new Integer(value) or (String s) -> new Integer(s)

LinkedList<Employee>::new

() -> new LinkedList<Employee>()

double[]::new

(int size) -> new double[size]

Listing 6 shows how to use a constructor reference to construct a MethodRefDemo instance, which is subsequently obtained and printed.

Listing 6 MethodRefDemo.java (Version 5)

import java.util.function.Supplier;

public class MethodRefDemo
{
   public static void main(String[] args)
   {
      Supplier<MethodRefDemo> supplier = MethodRefDemo::new;
      System.out.println(supplier.get());
   }
}

Constructor reference expression MethodRefDemo::new equates to lambda expression () -> new MethodRefDemo(). A lambda for instantiating MethodRefDemo is assigned to supplier. The subsequent supplier.get() expression executes this lambda, returning the MethodRefDemo instance, whose toString() method is implicitly called by System.out.println() to return its string representation, which is output to the standard output stream.

Compile Listing 6 (javac MethodRefDemo.java) and run this application (java MethodRefDemo). You should observe the following output, although the hash code might differ:

MethodRefDemo@5acf9800

You might be wondering how to instantiate a class with a parameterized constructor; for example, Employee(String name, int age). Listing 7 shows you how to accomplish this task.

Listing 7 MethodRefDemo.java (Version 6)

class Employee
{
   String name;
   Integer age;

   Employee()
   {
      name = "unknown";
      age = 100;
   }

   Employee(String name, Integer age)
   {
      this.name = name;
      this.age = age;
   }
}

@FunctionalInterface
interface EmployeeProvider
{
   Employee getEmployee(String name, Integer age);
}

public class MethodRefDemo
{
   public static void main(String[] args)
   {
      EmployeeProvider provider = Employee::new;
      Employee emp = provider.getEmployee("John Doe", 47);
      System.out.printf("Name: %s%n", emp.name);
      System.out.printf("Age: %d%n", emp.age);
   }
}

When it encounters Employee::new, the compiler infers the right constructor to call based on the context in which the constructor reference appears. Here, EmployeeProvider provider provides this context. Because this functional interface supplies a single abstract method whose parameter list matches the second Employee constructor, the compiler chooses that constructor. The constructor is then called (and the Employee object returned) by the subsequent getEmployee() method call.

Compile Listing 7 (javac MethodRefDemo.java) and run this application (java MethodRefDemo). You should observe the following output:

Name: John Doe
Age: 47
  • + Share This
  • 🔖 Save To Your Account