Java 8 Method References
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.
-
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
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
Other Extensions
Java 8 New Features