Sometimes, the actions you want to pass to other code already have a way of implementing them. Example:
Button.setonaction (event), System.out.println;
If you can just pass the println method to the Setonaction method, it's even better! Here's the revised code:
Button.setonaction (System.out::p rintln);
Expression System.out::p Rintln is a method reference , equivalent to a lambda expression:
X-System.out.println (x)
As the example code shows: operators separate the name of the method from the names of the objects or classes. The following three main use cases:
Object:: Instance method
Class:: Static method
Class:: Instance method
In the first two cases, a method reference is equivalent to a lambda expression that provides a method parameter. As mentioned earlier, System.out: The:p rintln is equivalent to SYSTEM.OUT.PRINTLN (x). Similarly, Math::p ow is equivalent to (x, y)-Math.pow (x, y). In the third case, the first parameter becomes the object that executes the method. For example, String::comparetoignorecase is equivalent to (x, y), X.comparetoignorecase (y).
Note: If you have more than one overloaded method with the same name, the compiler tries to find the most matching method from the context. For example, there are two versions of the Math.max method, one receives an integer as a parameter, and the other receives a value of type double. Which method to choose depends on the method parameters of the functional interface to which Math::max is converted. Similar to lambda expressions, method references do not exist independently, and they are often used to convert to instances of a functional interface.
You can also capture the This parameter in a method reference. For example, This::equals is equivalent to This.equals (x), X. You can also use super objects, such as: Super:: Instance methods. Example:
package java8;public class j2 { public static void Main (String[] args) { greeter g = new concurrentgreeter (); g.greet (); }} Class greeter { public void greet () { system.out.println ("hello world!"); }}class concurrentgreeter extends greeter{ @ Override public void greet () { //super represents the parent class object of the current class, not the parent instance object of the functional interface thread t = new thread (Super::greet); t.start (); }}
Package Java8;public class J3 {public static void main (string[] args) {Greeter1 g = new Greeter1 (); G.greet (); }}class Greeter1 {public void greet () {//this represents an object of the current class, not an instance object of the functional interface thread T = new Thread (this::p rinti NFO); T.start (); } public void Printinfo () {System.out.println ("Test success!!"); }}
Java8 lambda expression (method Reference)