forked from BruceEckel/OnJava8-Examples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCreator.java
More file actions
48 lines (41 loc) · 1.52 KB
/
Copy pathCreator.java
File metadata and controls
48 lines (41 loc) · 1.52 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
// reflection/pets/Creator.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Creates random Pets
package reflection.pets;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public abstract class Creator implements Supplier<reflection.pets.Pet> {
private Random rand = new Random(47);
// The different types of Pet to create:
public abstract List<Class<? extends reflection.pets.Pet>> types();
@Override
public reflection.pets.Pet get() { // Create one random Pet
int n = rand.nextInt(types().size());
try {
return types().get(n)
.getConstructor().newInstance();
} catch (InstantiationException |
NoSuchMethodException |
InvocationTargetException |
IllegalAccessException e) {
throw new RuntimeException(e);
}
}
public Stream<reflection.pets.Pet> stream() {
return Stream.generate(this);
}
public reflection.pets.Pet[] array(int size) {
return stream().limit(size).toArray(reflection.pets.Pet[]::new);
}
public List<reflection.pets.Pet> list(int size) {
return stream().limit(size)
.collect(Collectors.toCollection(ArrayList::new));
}
}