forked from BruceEckel/OnJava8-Examples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDynaFactory.java
More file actions
44 lines (43 loc) · 1.27 KB
/
DynaFactory.java
File metadata and controls
44 lines (43 loc) · 1.27 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
// patterns/trash/DynaFactory.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.
// Dynamic discovery of Trash types.
package patterns.trash;
import java.util.*;
import java.util.function.*;
import java.lang.reflect.*;
public class DynaFactory {
private Map<String, Constructor> constructors =
new HashMap<>();
private String packageName;
public DynaFactory(String packageName) {
this.packageName = packageName;
}
@SuppressWarnings("unchecked")
public
<T extends Trash> T create(TrashInfo info) {
try {
String typename =
"patterns." + packageName + "." + info.type;
return (T)constructors.computeIfAbsent(
typename, this::findConstructor
).newInstance(info.data);
} catch(Exception e) {
throw new RuntimeException(
"Cannot create() Trash: " + info, e);
}
}
private
Constructor findConstructor(String typename) {
try {
System.out.println("Loading " + typename);
return Class.forName(typename)
.getConstructor(double.class);
} catch(Exception e) {
throw new RuntimeException(
"Trash(double) Constructor Not Found: " +
typename, e);
}
}
}