Java 8 Method Reference
The method reference refers to a method by its name.
Method references can make language constructs more compact and concise, reducing redundant code.
The method reference uses a pair of colons ::.
Below, we have defined 4 methods in the Car class as examples to differentiate the references of 4 different methods in Java.
PackageJava8.cainiao; @FunctionalInterface Public InterfaceSupplier<t>{T get ();}classCar {//supplier is the interface of jdk1.8, which is used in conjunction with LAMDA. Public StaticCar Create (FinalSupplier<car>supplier) { returnSupplier.get (); } Public Static voidCollide (Finalcar car) {System.out.println ("Collided" +car.tostring ()); } Public voidFollow (FinalCar Another) {System.out.println ("Following the" +another.tostring ()); } Public voidrepair () {System.out.println ("Repaired" + This. toString ()); }}
1. Constructor reference: Its syntax is class::new, or the more general class< T >::new instance is as follows:
Final Car car = car.create (car::new ); Final list< car > Cars = arrays.aslist (car);
2. Static method Reference: Its syntax is Class::static_method, with the following example:
Cars.foreach (Car::collide);
3. Method reference for any object of a particular class: its syntax is the Class::method instance as follows:
Cars.foreach (Car::repair);
4. method Reference for a particular object: its syntax is the Instance::method instance as follows:
Final Car police = car.create (car::new ); Cars.foreach (police::follow);
Method Reference Instance
Enter the following code in the Java8tester3.java file:
PackageJava8.cainiao;Importjava.util.List;Importjava.util.ArrayList; Public classJava8tester3 { Public Static voidMain (String args[]) {List<String> names =NewArraylist<>(); Names.add ("Google"); Names.add ("Runoob"); Names.add ("Taobao"); Names.add ("Baidu"); Names.add ("Sina"); /*** In the example we will System.out::p Rintln method as a static method to reference*/Names.foreach (system.out::p rintln); }}
In the example we will System.out::p Rintln method as a static method to refer to.
Execute the above script and the output is:
Googlerunoobtaobaobaidusina
Java 8 new Features-Rookie tutorial (2)-java 8 method reference