1 4 package gnu.expr; 5 import gnu.mapping.*; 6 import java.util.*; 7 8 11 12 public class ModuleContext 13 { 14 static ModuleContext global = new ModuleContext(ModuleManager.instance); 15 ModuleManager manager; 16 17 public ModuleContext (ModuleManager manager) 18 { 19 this.manager = manager; 20 } 21 22 24 public static ModuleContext getContext () 25 { 26 return global; 27 } 28 29 public ModuleManager getManager () 30 { 31 return manager; 32 } 33 34 Hashtable table = new Hashtable(); 35 36 public Object checkInstance (ModuleInfo info) 37 { 38 return table.get(info.className); 39 } 40 41 42 public Object makeInstance (ModuleInfo info) 43 { 44 String cname = info.className; 45 Class clas; 46 try 47 { 48 clas = info.getModuleClass(); 49 } 50 catch (java.lang.ClassNotFoundException ex) 51 { 52 throw new WrappedException("cannot find module " + cname, ex); 53 } 54 55 Object inst; 56 try 57 { 58 try 59 { 60 inst = clas.getDeclaredField("$instance").get(null); 61 } 62 catch (NoSuchFieldException ex) 63 { 64 inst = clas.newInstance(); 66 } 67 } 68 catch (Throwable ex) 69 { 70 throw new WrappedException 71 ("exception while initializing module " + cname, ex); 72 } 73 setInstance(info, inst); 74 return inst; 75 } 76 77 78 public Object findInstance (ModuleInfo info) 79 { 80 Object inst = table.get(info.className); 81 if (inst == null || info.moduleClass == null 82 || ! info.moduleClass.isInstance(inst)) 83 inst = makeInstance(info); 84 return inst; 85 } 86 87 public void setInstance (ModuleInfo info, Object instance) 88 { 89 table.put(info.className, instance); 90 } 91 92 public ModuleInfo findFromInstance (Object instance) 93 { 94 Class instanceClass = instance.getClass(); 95 String className = instanceClass.getName(); 96 ModuleInfo info = manager.findWithClassName(className); 97 info.moduleClass = instanceClass; 98 setInstance(info, instance); 99 return info; 100 } 101 102 } 103 | Popular Tags |