forked from BruceEckel/OnJava8-Examples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApplyTest.java
More file actions
84 lines (77 loc) · 2.1 KB
/
ApplyTest.java
File metadata and controls
84 lines (77 loc) · 2.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// generics/ApplyTest.java
// (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
import java.util.*;
import java.util.function.*;
import onjava.*;
class Shape {
private static long counter = 0;
private final long id = counter++;
@Override
public String toString() {
return getClass().getSimpleName() + " " + id;
}
public void rotate() {
System.out.println(this + " rotate");
}
public void resize(int newSize) {
System.out.println(this + " resize " + newSize);
}
}
class Square extends Shape {}
class FilledList<T> extends ArrayList<T> {
public FilledList(Supplier<T> gen, int size) {
Suppliers.fill(this, gen, size);
}
}
public class ApplyTest {
public static void main(String[] args) throws Exception {
List<Shape> shapes =
Suppliers.create(ArrayList::new, Shape::new, 3);
Apply.apply(shapes, Shape.class.getMethod("rotate"));
Apply.apply(shapes,
Shape.class.getMethod("resize", int.class), 7);
List<Square> squares =
Suppliers.create(ArrayList::new, Square::new, 3);
Apply.apply(squares, Shape.class.getMethod("rotate"));
Apply.apply(squares,
Shape.class.getMethod("resize", int.class), 7);
Apply.apply(new FilledList<>(Shape::new, 3),
Shape.class.getMethod("rotate"));
Apply.apply(new FilledList<>(Square::new, 3),
Shape.class.getMethod("rotate"));
SimpleQueue<Shape> shapeQ = Suppliers.fill(
new SimpleQueue<>(), SimpleQueue::add,
Shape::new, 3);
Suppliers.fill(shapeQ, SimpleQueue::add,
Square::new, 3);
Apply.apply(shapeQ, Shape.class.getMethod("rotate"));
}
}
/* Output:
Shape 0 rotate
Shape 1 rotate
Shape 2 rotate
Shape 0 resize 7
Shape 1 resize 7
Shape 2 resize 7
Square 3 rotate
Square 4 rotate
Square 5 rotate
Square 3 resize 7
Square 4 resize 7
Square 5 resize 7
Shape 6 rotate
Shape 7 rotate
Shape 8 rotate
Square 9 rotate
Square 10 rotate
Square 11 rotate
Shape 12 rotate
Shape 13 rotate
Shape 14 rotate
Square 15 rotate
Square 16 rotate
Square 17 rotate
*/