Repository navigation
Expand file tree
/
Copy pathDynaFactory.java
More file actions
46 lines (41 loc) · 1.48 KB
/
Copy pathDynaFactory.java
File metadata and controls
46 lines (41 loc) · 1.48 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
// 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.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;
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 patterns.trash.Trash> T create(patterns.trash.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);
}
}
}