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
38 lines (37 loc) · 1.2 KB
/
Creator.java
File metadata and controls
38 lines (37 loc) · 1.2 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
// 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.util.*;
import java.util.function.*;
import java.util.stream.*;
import java.lang.reflect.InvocationTargetException;
public abstract class Creator implements Supplier<Pet> {
private Random rand = new Random(47);
// The different types of Pet to create:
public abstract List<Class<? extends Pet>> types();
@Override public 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<Pet> stream() {
return Stream.generate(this);
}
public Pet[] array(int size) {
return stream().limit(size).toArray(Pet[]::new);
}
public List<Pet> list(int size) {
return stream().limit(size)
.collect(Collectors.toCollection(ArrayList::new));
}
}