Java 8 Method References
A method reference points to a method by its name.
Method references 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 kinds of method references in Java.
package
com
.
runoob
.
main
; @
FunctionalInterface
public
interface
Supplier
<
T
{
T
get
(
);
}
class
Car
{
//
Supplier is a jdk1.8 interface, used here together with lambda
public
static
Car
create
(
final
Supplier
<
Car
supplier
)
{
return
supplier.
get
(
)
;
}
public
static
void
collide
(
final
Car
car
)
{
System
.
out
.
println
(
"
Collided
"
car
.
toString
(
)
)
;
}
public
void
follow
(
final
Car
another
)
{
System
.
out
.
println
(
"
Following the
"
another
.
toString
(
)
)
;
}
public
void
repair
(
)
{
System
.
out
.
println
(
"
Repaired
"
this
.
toString
(
)
)
;
}
}
-
Constructor reference:Its syntax is Class::new, or more generally Class< T >::new, as in the following example:
Static method reference:Its syntax is Class::static_method, as in the following example:
Method reference to any object of a particular class:Its syntax is Class::method, as in the following example:
Method reference to a particular object:Its syntax is instance::method, as in the following example:
Method Reference Example
Enter the following code in the Java8Tester.java file:
Java8Tester.java file
import
java
.
util
.
List
;
import
java
.
util
.
ArrayList
;
public
class
Java8Tester
{
public
static
void
main
(
String
args
[
]
)
{
List
<
String
names
=
new
ArrayList
(
);
names
.
add
(
"
"
)
;
names
.
add
(
"
Runoob
"
)
;
names
.
add
(
"
Taobao
"
)
;
names
.
add
(
"
Baidu
"
)
;
names
.
add
(
"
Sina
"
)
;
names
.
forEach
(
System
.
out
::
println
)
;
}
}
In the example we reference the System.out::println method as a static method.
Executing the above script produces the following output:
$ javac Java8Tester.java
$ java Java8Tester
Google
Runoob
Taobao
Baidu
Sina
Java 8 New Features