01: // Copyright (c) 2005 Per M.A. Bothner.
02: // This is free software; for terms and warranty disclaimer see ./COPYING.
03:
04: package gnu.expr;
05:
06: import gnu.mapping.*;
07: import java.util.*;
08:
09: /** Maps modules to module instances.
10: * Given a class, species a specific instance object for that class.
11: */
12:
13: public class ModuleContext {
14: static ModuleContext global = new ModuleContext(
15: ModuleManager.instance);
16: ModuleManager manager;
17:
18: public ModuleContext(ModuleManager manager) {
19: this .manager = manager;
20: }
21:
22: /** For now returns the shared global ModuleContext.
23: * Later provide a means for thread-specific overriding. */
24: public static ModuleContext getContext() {
25: return global;
26: }
27:
28: public ModuleManager getManager() {
29: return manager;
30: }
31:
32: Hashtable table = new Hashtable();
33:
34: public Object checkInstance(ModuleInfo info) {
35: return table.get(info.className);
36: }
37:
38: /** Allocate a new instance of the class corresponding to the argument. */
39: public Object makeInstance(ModuleInfo info) {
40: String cname = info.className;
41: Class clas;
42: try {
43: clas = info.getModuleClass();
44: } catch (java.lang.ClassNotFoundException ex) {
45: throw new WrappedException("cannot find module " + cname,
46: ex);
47: }
48:
49: Object inst;
50: try {
51: try {
52: inst = clas.getDeclaredField("$instance").get(null);
53: } catch (NoSuchFieldException ex) {
54: // Not a static module - create a new instance.
55: inst = clas.newInstance();
56: }
57: } catch (Throwable ex) {
58: throw new WrappedException(
59: "exception while initializing module " + cname, ex);
60: }
61: setInstance(info, inst);
62: return inst;
63: }
64:
65: /** If there is no instance of the argument's class, allocated one. */
66: public Object findInstance(ModuleInfo info) {
67: Object inst = table.get(info.className);
68: if (inst == null || info.moduleClass == null
69: || !info.moduleClass.isInstance(inst))
70: inst = makeInstance(info);
71: return inst;
72: }
73:
74: public void setInstance(ModuleInfo info, Object instance) {
75: table.put(info.className, instance);
76: }
77:
78: public ModuleInfo findFromInstance(Object instance) {
79: Class instanceClass = instance.getClass();
80: String className = instanceClass.getName();
81: ModuleInfo info = manager.findWithClassName(className);
82: info.moduleClass = instanceClass;
83: setInstance(info, instance);
84: return info;
85: }
86:
87: }
|