Java 8 Method References

Java 8 新特性Java 8 New Features


A method reference points to a method by its name.

Method references can make language constructs more compact and concise, reducing redundant code.

Method references use a pair of colons:: 。

Below, we define 4 methods in the Car class as examples to distinguish the 4 different types of method references in Java.

package com.example.main; @FunctionalInterface public interface Supplier<T> { T get(); } class Car { //Supplier is an interface in JDK 1.8, used here together with lambda. public static Car create(final Supplier<Car> supplier) { return supplier.get(); } public static void collide(final Car car) { System.out.println("Collided " + car.toString()); } public void follow(final Car another) { System.out.println("Following the " + another.toString()); } public void repair() { System.out.println("Repaired " + this.toString()); } }
  • Constructor Reference:Its syntax is Class::new, or more generally Class< T >::new. Example:

    final Car car = Car.create( Car::new ); final List< Car > cars = Arrays.asList( car );
  • Static Method Reference:Its syntax is Class::static_method. Example:

    cars.forEach( Car::collide );
  • Method reference to an arbitrary object of a particular class:Its syntax is Class::method. Example:

    cars.forEach( Car::repair );
  • Method reference to a specific object:Its syntax is instance::method. Example:

    final Car police = Car.create( Car::new ); cars.forEach( police::follow );

Method Reference Examples

Enter the following code in the Java8Tester.java file:

Java8Tester.java File

import java.util.List; import java.util.ArrayList; public class Java8Tester { public static void main(String args[]){ List<String> names = new ArrayList(); names.add("Google"); names.add("Example"); names.add("Taobao"); names.add("Baidu"); names.add("Sina"); names.forEach(System.out::println); } }

In the example, we reference the System.out::println method as a static method.

Execute the above script, and the output is:

$ javac Java8Tester.java 
$ java Java8Tester
Google
Example
Taobao
Baidu
Sina

Java 8 新特性Java 8 New Features

Other Extensions