OnJava8-Examples/functional/MethodReferences.java

54 lines
1.1 KiB
Java
Raw Normal View History

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.*;
interface Callable { // [1]
2015-12-02 09:20:27 -08:00
void call(String s);
}
class Describe {
void show(String msg) { // [2]
2015-12-02 09:20:27 -08:00
System.out.println(msg);
}
}
2015-06-15 17:47:35 -07:00
public class MethodReferences {
static void hello(String name) { // [3]
2015-12-02 09:20:27 -08:00
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]
2015-12-02 09:20:27 -08:00
System.out.println(about + " " + msg);
}
}
static class Helper {
static void assist(String msg) { // [5]
2015-12-02 09:20:27 -08:00
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]
2015-12-02 09:20:27 -08:00
c = MethodReferences::hello; // [8]
2015-12-02 09:20:27 -08:00
c.call("Bob");
c = new Description("valuable")::help; // [9]
2015-12-02 09:20:27 -08:00
c.call("information");
2015-06-15 17:47:35 -07:00
c = Helper::assist; // [10]
2015-12-02 09:20:27 -08:00
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
*/