Method references point to a method by its name.
Method references can make the language structure compact and concise, reducing redundant code.
The method reference uses a pair of colons :: .
Below, we define 4 methods in the Car class as examples to distinguish the references of 4 different methods in Java.
package com.runoob.main;
@FunctionalInterface
public interface Supplier<T> {
T get();
}
class Car {
//Supplier jdk1.8 interface is used here together and lamd
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 general Class<T>::new instances are as follows:final Car car = Car.create( Car::new ); final List< Car > cars = Arrays.asList( car );
- Static method reference: Its syntax is Class::static_method, an instance is as follows:cars.forEach( Car::collide );
- A method reference to an arbitrary object of a particular class: Its syntax is an instance of Class::method as follows:cars.forEach( Car::repair );
- Method reference for a specific object: Its syntax is instance::method instance is as follows:final Car police = Car.create( Car::new ); cars.forEach( police::follow );
Method reference instance
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 names = new ArrayList();
names.add("Google");
names.add("Facebook");
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, the output is:
$ javac Java8Tester.java $ java Java8Tester Google Facebook Taobao Baidu Sina
Comments
Post a Comment