English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Method references point to a method by the method's name.
Method references make the language structure more compact and concise, reducing redundant code.
Method references are denoted by a pair of colons :: .
Below, we define the 4 This method is used as an example to differentiate in Java 4 different method references.
package com.w3codebox.main; @FunctionalInterface public interface Supplier<T> { T get(); } class Car { //Supplier is a jdk1.8interface, here used with lambda together 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, for example:
final Car car = Car.create(Car::new); final List<Car> cars = Arrays.asList(car);
Static method reference:Its syntax is Class::static_method, for example:
cars.forEach(Car::collide);
Method reference to any object of a specific class:Its syntax is Class::method, for example:
cars.forEach(Car::repair);
Method reference to a specific object:Its syntax is instance::method, for example:
final Car police = Car.create(Car::new); cars.forEach(police::follow);
In Java8Tester.java file input the following code:
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("w3codebox"); names.add("Taobao"); names.add("Baidu"); names.add("Sina"); names.forEach(System.out::println); } }
In this example, we use the System.out::println method as a static method reference.
Execute the above script, and the output will be:
$ javac Java8Tester.java $ java Java8Tester Google w3codebox Taobao Baidu Sina