New feature in Java 8 - method reference

Java 8 Feature - Method References

This article is translated from: Java 8 Method Reference

Method References

A new feature called method reference is provided in Java 8. Method references are used to reference other methods on a functional interface. It is a simpler form of Lambda expression. When you use Lambda expressions only to reference another method, you can replace these statements with method references. In this tutorial, we will explain the concept of method reference in detail.

Type of method reference

In Java, method references have the following types:

  1. Reference a static method
  2. Reference an instance method
  3. Reference a constructor

Reference static method

You can reference static methods in a class. The following is the syntax and examples of static method references.

grammar

ClassName::staticMethodName

Example 1

In the following example, we will define a functional interface and reference a static method to implement the eat() method in the interface.

interface Eatable {
    void eat();
}

public class MethodReference {
    public static void eatSomething() {
        System.out.println("I'm having a meal...");
    }

    public static void main(String[] args) {
        // Reference static method
        Eatable eatable = MethodReference::eatSomething;
        // It is equivalent to the following Lambda expression
        Eatable eatable1 = () -> MethodReference.eatSomething();
        eatable.eat();
        eatable1.eat();
    }
}

Operation results:

I'm having a meal...
I'm having a meal...

Example 2

In this example, we use the built-in functional interface Runnable in Java to reference a static method.

public class MethodReference2 {
    public static void threadStatus() {
        System.out.println("The thread is running...");
    }

    public static void main(String[] args) {
        // Use the run method in Runnable to reference the static method threadStatus()
        Thread t2 = new Thread(MethodReference2::threadStatus);
        t2.start();
    }
}

Operation results:

The thread is running..

Example 3

You can also use the corresponding parameter list to refer to the specified method in the method overload. In the following example, we define three overloaded methods for method references.

import java.util.function.BiFunction;

class Arithmetic {
    // int, int
    public static int add(int a, int b) {
        return a + b;
    }

    // int, float
    public static float add(int a, float b) {
        return a + b;
    }

    // float, float
    public static float add(float a, float b) {
        return a + b;
    }
}

public class MethodReference3 {
    public static void main(String[] args) {
        // Two arguments of type Integer and a return value of type Integer
        BiFunction<Integer, Integer, Integer> adder1 = Arithmetic::add;
        // A parameter list of type (Integer, Float) and a return value of type Float
        BiFunction<Integer, Float, Float> adder2 = Arithmetic::add;
        // A list of parameters of type (Float, Float) and a return value of type Float
        BiFunction<Float, Float, Float> adder3 = Arithmetic::add;
        int result1 = adder1.apply(10, 20);
        float result2 = adder2.apply(10, 20.0f);
        float result3 = adder3.apply(10.0f, 20.0f);
        System.out.println(result1);
        System.out.println(result2);
        System.out.println(result3);
    }
}

Operation results:

30
30.0
30.0

Reference instance method

Like static methods, you can also reference instance methods. In the following example, we will show how to make a method reference to an instance method.

grammar

objectInstance::instanceMethodName

Example

In this example, we will reference a non static method of an object. You can reference methods through class objects or anonymous objects.

interface Eatable {
    void eat();
}

public class MethodReference4 {
    public void eatSomething() {
        System.out.println("xx I am eating...");
    }

    public static void main(String[] args) {
        // Create an object instance
        MethodReference4 methodReference = new MethodReference4();
        // Reference non static method by instance name
        Eatable eatable = methodReference::eatSomething;
        eatable.eat();

        // Non static methods that reference anonymous objects
        Eatable eatable2 = new MethodReference4()::eatSomething;
        eatable2.eat();
    }
}

Operation results:

xx I am eating...
xx I am eating...

Reference construction method

You can use the new keyword to reference a constructor. Here, we use a functional interface to reference a constructor.

grammar

ClassName::new

Example

interface Messageable {
    Message getMessage(String msg);
}

class Message {
    Message(String msg) {
        System.out.println(msg);
    }
}

public class MethodReference5 {
    public static void main(String[] args) {
        // Reference a constructor
        Messageable hello = Message::new;
        hello.getMessage("Hello");
    }
}

summary

Through these examples, we can find that the method reference is to forward the parameters of the Lambda expression directly to the referenced method, and return the return value of the method as the return value of the Lambda expression (the construction method returns the object itself).

Posted by ryadex on Tue, 30 Nov 2021 09:14:57 -0800