Home > Articles > Programming > Java

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

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020