2015-11-14 16:18:05 -08:00
|
|
|
// functional/MethodReferences.java
|
2015-12-15 11:47:04 -08:00
|
|
|
// (c)2016 MindView LLC: see Copyright.txt
|
2015-11-15 15:51:35 -08:00
|
|
|
// We make no guarantees that this code is fit for any purpose.
|
2016-09-23 13:23:35 -06:00
|
|
|
// Visit http://OnJava8.com for more book information.
|
2015-06-15 17:47:35 -07:00
|
|
|
import java.util.*;
|
|
|
|
|
2015-12-02 09:20:27 -08:00
|
|
|
interface Callable { // (1)
|
|
|
|
void call(String s);
|
|
|
|
}
|
|
|
|
|
|
|
|
class Describe {
|
|
|
|
void show(String msg) { // (2)
|
|
|
|
System.out.println(msg);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-06-15 17:47:35 -07:00
|
|
|
public class MethodReferences {
|
2015-12-02 09:20:27 -08:00
|
|
|
static void hello(String name) { // (3)
|
|
|
|
System.out.println("Hello, " + name);
|
|
|
|
}
|
2015-06-15 17:47:35 -07:00
|
|
|
static class Description {
|
2015-12-02 09:20:27 -08:00
|
|
|
String about;
|
|
|
|
public Description(String desc) { about = desc; }
|
|
|
|
void help(String msg) { // (4)
|
|
|
|
System.out.println(about + " " + msg);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
static class Helper {
|
|
|
|
static void assist(String msg) { // (5)
|
|
|
|
System.out.println(msg);
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
public static void main(String[] args) {
|
2015-12-02 09:20:27 -08:00
|
|
|
Describe d = new Describe();
|
|
|
|
Callable c = d::show; // (6)
|
|
|
|
c.call("call()"); // (7)
|
|
|
|
|
|
|
|
c = MethodReferences::hello; // (8)
|
|
|
|
c.call("Bob");
|
|
|
|
|
|
|
|
c = new Description("valuable")::help; // (9)
|
|
|
|
c.call("information");
|
2015-06-15 17:47:35 -07:00
|
|
|
|
2015-12-02 09:20:27 -08:00
|
|
|
c = Helper::assist; // (10)
|
|
|
|
c.call("Help!");
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
2015-09-07 11:44:36 -06:00
|
|
|
}
|
|
|
|
/* Output:
|
2015-12-02 09:20:27 -08:00
|
|
|
call()
|
|
|
|
Hello, Bob
|
|
|
|
valuable information
|
|
|
|
Help!
|
2015-09-07 11:44:36 -06:00
|
|
|
*/
|