DEV Community

Cover image for Method Reference
Yasushi Takehara
Yasushi Takehara

Posted on • Updated on

Method Reference

Java8 has a function named "Method Reference" that points to a method.

Before Java8

It needed to create an object, which implements an interface, to refer a method.

public class Main {
    interface IGreeter {
        void greet(String name);
    }

    static void delegate(IGreeter iGreeter, String name){
        iGreeter.greet(name);
    }

    public static void main(String[] args) throws Exception {
        // need to put an object implemented the interface 'IGreeter'
        delegate(new IGreeter(){
            public void greet(String name){
                System.out.println("Hello, " + name + "."); // => Hello, Taro.
            }
        }, "Taro");
    }
}
Enter fullscreen mode Exit fullscreen mode

From Java8

Programmers can use 'ClassName(ObjectVariableName)::MethodName' to refer it.

public class Main {

    @FunctionalInterface // This annotation can be omitted
    interface IGreeter {
        void greet(String name);
    }

    // This method can work instead of the above greet method.
    static void referredGreet(String name){
        System.out.println("Hello, " + name + ".");
    }

    static void delegate(IGreeter iGreeter, String name){
        iGreeter.greet(name);
    }

    public static void main(String[] args) throws Exception {
        // can put a method reference as 'ClassName::MethodName'
        delegate(Main::referredGreet, "Taro"); // => Hello, Taro.
    }
}

Enter fullscreen mode Exit fullscreen mode

The most notable point is the name of the referred method "referredGreet" can be different from the one "greet" in the interface.

There are two rules.

  1. The interface must have only one method.
  2. The method of the interface must match the referred one in terms of 'type' of arguments and return value.

The referred method can use the parent type.
For example,

static void referredGreet(String name){

can be

static void referredGreet(Object name){

In other words, interface method can use sub type of the one of the referred method.

The method reference helps developers to write code simpler
For example,

List<String> list = Arrays.asList("aaa", "bbb", "ccc");
list.forEach(System.out::println); // => aaa
//bbb
//ccc
Enter fullscreen mode Exit fullscreen mode

This the spec of 'forEach' method.
https://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html#forEach-java.util.function.Consumer-

The referred method (Consumer) must have one argument and void-return.
https://docs.oracle.com/javase/8/docs/api/java/util/function/Consumer.html
System.out::println meets the condition. That's why it can be set to 'forEach'.

Reference

改訂2版 パーフェクトJava
https://gihyo.jp/book/2014/978-4-7741-6685-8

Top comments (0)