6.3.4 method reference and 6.3.4 reference
Sometimes, you may already have a ready-made method to complete an action that you want to pass to other code.
For example, suppose you want to print the event object as long as a timer event occurs. Of course, you can call:
Timer t =new Timer(1000,event -> System.out.println(event));
However, it would be better to pass the println method directly to the Timer constructor. The procedure is as follows:
Timer t = new Timer(1000,System.out.println(event));
Expression System. out: println is a method reference. It is equivalent to lambda expression x-> System. out. println (x ).
Let's look at an example to sort strings, regardless of the case. You can pass the following method expression:
Arrays. sort (strings, String: compareToIgnoreCase)
From these examples, we can use the: operator to separate the method name from the object or class name. There are three main cases:
Object: instanceMethod
Class: staticMethod
Class: instanceMethod
In the first two cases, a method reference is equivalent to a lambda expression that provides method parameters. As mentioned above, System. out: println is equivalent to x-> System. out. println (x ). similarly, Math: pow is equivalent to (x, y)-> Math. pow (x, y ).
In the third case, the first parameter will become the target of the method. For example, String: compareToIgnoreCase is equivalent to (x, y)-> x. compareToIgnoreCase (y ).
Similar to lambda expressions, method references cannot exist independently and are always converted to functional interface instances. You can use this parameter in method reference, for example:
This: equals is equivalent to x-> this. equals (x ). It is also legal to use super. The following Method Expression
Super: instanceMethod
If this is used as the target, the superclass version of the given method is called.
Example:
1 class Greeter 2 { 3 public void greet() 4 { 5 System.out.println("Hello,world!"); 6 } 7 } 8 class TimedGreeter extends Greeter 9 {10 public void greet()11 {12 Timer t =new Timer (1000,super::greet);13 t.start();14 }15 }
When the TimerGreeter. greet method starts to be executed, a Timer is constructed, and the super: greet method is executed every time the Timer replies. This method calls the superclass greet method.