Method references
The method referred to by the name of the method to point to a method.
The method reference can be made more compact and simple construction of the language, to reduce redundant code.
Method references a pair of colon ::.
Examples
- Here, we define four classes method Car cited as an example in Java distinguish four different methods.
package com.nowcoder.main;
@FunctionalInterface
public interface Supplier<T> {
T get();
}
class Car {
//Supplier是jdk1.8的接口,这里和lamda一起使用了
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: The syntax is Class :: new, or more generally Class <T> :: new examples are as follows:
final Car car = Car.create( Car::new );
final List< Car > cars = Arrays.asList( car );
- Static method referenced: its syntax is Class :: static_method, examples are as follows:
cars.forEach( Car::collide );
- The method of any particular class object reference: The syntax is as follows Class :: method Example:
cars.forEach( Car::repair );
- The method of a specific object reference: The syntax is as follows Example instance :: method:
final Car police = Car.create( Car::new );
cars.forEach( police::follow );
Method references instance of
Enter the following code in 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("Nowcoder");
names.add("Taobao");
names.add("Baidu");
names.add("Sina");
names.forEach(System.out::println);
}
}
Example we will System.out :: println method as a static method to reference.
The implementation of the above script, output is:
$ javac Java8Tester.java
$ java Java8Tester
Google
Nowcoder
Taobao
Baidu
Sina
Other new features (Update)
Java8 new features -Lambad expression
Java8 new feature - function interface
Java8 new features - the default method