With Lambda expressions Java 8 has new power for developing smart and fast applications. If you don’t know how lambda expressions works just take a look a link above.
Sometimes, there is already a method that carries out exactly the action that you’d like to pass on to some other code. For example, suppose you simply want to print the event object whenever a button is clicked. You can use code below:
1 2 |
button.setOnAction(event -> System.out.println(event)); |
But there is simpler way to do it. If you want to just pass the println
method to the setOnAction
method you can use method references:
1 2 |
button.setOnAction(System.out::println); |
This is equivalent to code above.
As you can see from these examples, the ::
operator separates the method name from the name of an object or class. There are three principal classes:
object::instanceMethod
Class::staticMethod
Class::instanceMethod
Two first cases works the same as in the example above. Method reference is equivalent to a lambda expression that supplies the parameters of the method.
System.out::println
is equivalent to x -> System.out.println(x)
Similarly
Math::pow
is equivalent to (x, y) -> Math.pow(x, y)
as described at second case above.
The last one case is different from these above. The first parameter becomes the target of the method.
String::compareToIgnoreCase
is the same as (x, y) -> x.compareToIgnoreCase(y)
You can use this
and super
keywords. this
refer to an enclosing class.
You can treat it as follow:
1 2 3 |
EnclosingClass.this::method EnclosingClass.super::method |
Example:
1 2 |
Thread t = new Thread(super::doSomething()); |
Constructor references
You can use contructor references as well. It’s just like method references, except that the name of the method is new
1 2 |
Button::new |
One another reference is for arrays. You can form contructor reference with array type. For example: int[]::new
is a contructor reference with one parameter: the length of the array. It’s equivalent to the lambda expression x -> new int[x]
.
.