Method Reference in Java 8


In Java, method reference is a feature introduced in Java 8 that allows you to refer to a method by its name instead of invoking it directly. It provides a concise syntax for passing methods as arguments to functional interfaces, which are interfaces that have only one abstract method.

Understanding Method Reference

Method references can be used in place of lambda expressions when the lambda expression simply calls an existing method. They are especially useful when working with functional interfaces like Consumer, Supplier, or Predicate, where you need to pass a method that matches the functional interface’s abstract method signature.

Syntax of Method Reference

The syntax of method reference follows the Class::methodName or Instance::methodName format. There are four main types of method references:

1. Reference to a static method

ClassName::staticMethodName

2. Reference to an instance method of a particular object

objectReference::instanceMethodName

3. Reference to an instance method of an arbitrary object of a particular type

ClassName::instanceMethodName

4. Reference to a constructor

ClassName::new

Let’s have a look on the below example that demonstrates the usage of method references.

1. Reference to a static method

Static method references are useful when you want to refer to static methods defined in a class. The referenced method must have the same parameter types and return type as the functional interface being used.

MRExample.java
package org.websparrow;

public class MRExample {
    public static void main(String[] args) {
        Printer printer = StringUtils::printMessage; // Method reference
        printer.print("Hello, Websparrow!");
        // Output: Hello, Websparrow!
    }
}


// Functional interface
interface Printer {
    void print(String message);
}

// Static method
class StringUtils {
    static void printMessage(String message) {
        System.out.println(message);
    }
}

2. Reference to an instance method of a particular object

This type of method reference allows us to refer to an instance method of a specific object. The referenced method must have the same parameter types and return type as the functional interface being used.

MRExample2.java
package org.websparrow;


public class MRExample2 {
    public static void main(String[] args) {
        MathUtils mathUtils = new MathUtils();
        Calculator calculator = mathUtils::sum; // Method reference
        int result = calculator.calculate(5, 7); // Invokes mathUtils.sum(5, 7)
        System.out.println(result); // Output: 12
    }
}

// Functional interface
interface Calculator {
    int calculate(int a, int b);
}

// Calculator class
class MathUtils {
    int sum(int a, int b) {
        return a + b;
    }
}

Post you may like: Java StringJoiner Class: Simplify String Concatenation

3. Reference to an instance method of an arbitrary object of a particular type

In this type of method reference, the referenced method is an instance method, but the object on which it is invoked is determined at runtime. The first parameter of the method reference becomes the target object, and the remaining parameters are passed as arguments to the referenced method.

MRExample3.java
package org.websparrow;


public class MRExample3 {
    public static void main(String[] args) {
        Converter converter = Integer::parseInt; // Method reference
        int result = converter.convert("42"); // Invokes Integer.parseInt("42")
        System.out.println(result); // Output: 42
    }
}


// Functional interface
interface Converter {
    int convert(String value);
}

// Converter class
class IntegerConverter {
    int convertToInt(String value) {
        return Integer.parseInt(value);
    }
}

4. Reference to a constructor

Method reference also allows us to refer to constructors. The syntax is similar to referencing static methods, where we use the class name followed by ::new.

MRExample4.java
package org.websparrow;


public class MRExample4 {
    public static void main(String[] args) {
        // Method reference to constructor
        PersonFactory personFactory = Person::new;
        // Invokes new Person("Atul Rai")
        Person person = personFactory.create("Atul Rai");
        System.out.println(person.name); // Output: Atul Rai
    }
}

// Person class
class Person {
    String name;

    Person(String name) {
        this.name = name;
    }
}

// Functional interface
interface PersonFactory {
    Person create(String name);
}

Summary

Method references provide a powerful way to simplify code by leveraging existing methods and promoting functional programming in Java.

References

  1. Method References- JavaDoc
  2. Java Objects Class Example

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.