PageRenderTime 52ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/jEdit/tags/jedit-4-2-pre4/bsh/BshClassManager.java

#
Java | 507 lines | 227 code | 47 blank | 233 comment | 40 complexity | bdf7a6a8c732fa9d8d5f9c03b1580e5f MD5 | raw file
Possible License(s): BSD-3-Clause, AGPL-1.0, Apache-2.0, LGPL-2.0, LGPL-3.0, GPL-2.0, CC-BY-SA-3.0, LGPL-2.1, GPL-3.0, MPL-2.0-no-copyleft-exception, IPL-1.0
  1. /*****************************************************************************
  2. * *
  3. * This file is part of the BeanShell Java Scripting distribution. *
  4. * Documentation and updates may be found at http://www.beanshell.org/ *
  5. * *
  6. * Sun Public License Notice: *
  7. * *
  8. * The contents of this file are subject to the Sun Public License Version *
  9. * 1.0 (the "License"); you may not use this file except in compliance with *
  10. * the License. A copy of the License is available at http://www.sun.com *
  11. * *
  12. * The Original Code is BeanShell. The Initial Developer of the Original *
  13. * Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
  14. * (C) 2000. All Rights Reserved. *
  15. * *
  16. * GNU Public License Notice: *
  17. * *
  18. * Alternatively, the contents of this file may be used under the terms of *
  19. * the GNU Lesser General Public License (the "LGPL"), in which case the *
  20. * provisions of LGPL are applicable instead of those above. If you wish to *
  21. * allow use of your version of this file only under the terms of the LGPL *
  22. * and not to allow others to use your version of this file under the SPL, *
  23. * indicate your decision by deleting the provisions above and replace *
  24. * them with the notice and other provisions required by the LGPL. If you *
  25. * do not delete the provisions above, a recipient may use your version of *
  26. * this file under either the SPL or the LGPL. *
  27. * *
  28. * Patrick Niemeyer (pat@pat.net) *
  29. * Author of Learning Java, O'Reilly & Associates *
  30. * http://www.pat.net/~pat/ *
  31. * *
  32. *****************************************************************************/
  33. package bsh;
  34. import java.net.*;
  35. import java.util.*;
  36. import java.io.IOException;
  37. import java.io.*;
  38. import java.lang.reflect.Method;
  39. import java.lang.reflect.Modifier;
  40. /**
  41. BshClassManager manages all classloading in BeanShell.
  42. It also supports a dynamically loaded extension (bsh.classpath package)
  43. which allows classpath extension and class file reloading.
  44. Currently the extension relies on 1.2 for BshClassLoader and weak
  45. references.
  46. See http://www.beanshell.org/manual/classloading.html for details
  47. on the bsh classloader architecture.
  48. <p>
  49. Bsh has a multi-tiered class loading architecture. No class loader is
  50. used unless/until the classpath is modified or a class is reloaded.
  51. <p>
  52. */
  53. /*
  54. Implementation notes:
  55. Note: we may need some synchronization in here
  56. Note on version dependency: This base class is JDK 1.1 compatible,
  57. however we are forced to use weak references in the full featured
  58. implementation (the optional bsh.classpath package) to accomodate all of
  59. the fleeting namespace listeners as they fall out of scope. (NameSpaces
  60. must be informed if the class space changes so that they can un-cache
  61. names).
  62. <p>
  63. Perhaps a simpler idea would be to have entities that reference cached
  64. types always perform a light weight check with a counter / reference
  65. value and use that to detect changes in the namespace. This puts the
  66. burden on the consumer to check at appropriate times, but could eliminate
  67. the need for the listener system in many places and the necessity of weak
  68. references in this package.
  69. <p>
  70. */
  71. public class BshClassManager
  72. {
  73. /** Identifier for no value item. Use a hashtable as a Set. */
  74. private static Object NOVALUE = new Object();
  75. /**
  76. An external classloader supplied by the setClassLoader() command.
  77. */
  78. private ClassLoader externalClassLoader;
  79. /**
  80. Global cache for things we know are classes.
  81. Note: these should probably be re-implemented with Soft references.
  82. (as opposed to strong or Weak)
  83. */
  84. protected transient Hashtable absoluteClassCache = new Hashtable();
  85. /**
  86. Global cache for things we know are *not* classes.
  87. Note: these should probably be re-implemented with Soft references.
  88. (as opposed to strong or Weak)
  89. */
  90. protected transient Hashtable absoluteNonClasses = new Hashtable();
  91. /**
  92. Caches for resolved object and static methods.
  93. We keep these maps separate to support fast lookup in the general case
  94. where the method may be either.
  95. */
  96. protected transient Hashtable resolvedObjectMethods = new Hashtable();
  97. protected transient Hashtable resolvedStaticMethods = new Hashtable();
  98. /**
  99. Create a new instance of the class manager.
  100. Class manager instnaces are now associated with the interpreter.
  101. @see bsh.Interpreter.getClassManager()
  102. @see bsh.Interpreter.setClassLoader( ClassLoader )
  103. */
  104. public static BshClassManager createClassManager()
  105. {
  106. BshClassManager manager;
  107. // Do we have the necessary jdk1.2 packages and optional package?
  108. if ( Capabilities.classExists("java.lang.ref.WeakReference")
  109. && Capabilities.classExists("java.util.HashMap")
  110. && Capabilities.classExists("bsh.classpath.ClassManagerImpl")
  111. )
  112. try {
  113. // Try to load the module
  114. // don't refer to it directly here or we're dependent upon it
  115. Class clas = Class.forName( "bsh.classpath.ClassManagerImpl" );
  116. manager = (BshClassManager)clas.newInstance();
  117. } catch ( Exception e ) {
  118. throw new InterpreterError("Error loading classmanager: "+e);
  119. }
  120. else
  121. manager = new BshClassManager();
  122. return manager;
  123. }
  124. public boolean classExists( String name ) {
  125. return ( classForName( name ) != null );
  126. }
  127. /**
  128. Load the specified class by name, taking into account added classpath
  129. and reloaded classes, etc.
  130. @return the class or null
  131. */
  132. public Class classForName( String name ) {
  133. try {
  134. return plainClassForName( name );
  135. } catch ( ClassNotFoundException e ) {
  136. return null;
  137. }
  138. }
  139. /**
  140. Perform a plain Class.forName() or call the externally provided
  141. classloader.
  142. If a BshClassManager implementation is loaded the call will be
  143. delegated to it, to allow for additional hooks.
  144. <p/>
  145. This simply wraps that bottom level class lookup call and provides a
  146. central point for monitoring and handling certain Java version
  147. dependent bugs, etc.
  148. @see #classForName( String )
  149. @return the class
  150. */
  151. public Class plainClassForName( String name )
  152. throws ClassNotFoundException
  153. {
  154. Class c = null;
  155. try {
  156. if ( externalClassLoader != null )
  157. c = externalClassLoader.loadClass( name );
  158. else
  159. c = Class.forName( name );
  160. cacheClassInfo( name, c );
  161. /*
  162. Original note: Jdk under Win is throwing these to
  163. warn about lower case / upper case possible mismatch.
  164. e.g. bsh.console bsh.Console
  165. Update: Prior to 1.3 we were squeltching NoClassDefFoundErrors
  166. which was very annoying. I cannot reproduce the original problem
  167. and this was never a valid solution. If there are legacy VMs that
  168. have problems we can include a more specific test for them here.
  169. */
  170. } catch ( NoClassDefFoundError e ) {
  171. throw noClassDefFound( name, e );
  172. }
  173. return c;
  174. }
  175. /**
  176. Get a resource URL using the BeanShell classpath
  177. @param path should be an absolute path
  178. */
  179. public URL getResource( String path )
  180. {
  181. if ( externalClassLoader != null )
  182. {
  183. // classloader wants no leading slash
  184. return externalClassLoader.getResource( path.substring(1) );
  185. } else
  186. return Interpreter.class.getResource( path );
  187. }
  188. /**
  189. Get a resource stream using the BeanShell classpath
  190. @param path should be an absolute path
  191. */
  192. public InputStream getResourceAsStream( String path )
  193. {
  194. if ( externalClassLoader != null )
  195. {
  196. // classloader wants no leading slash
  197. return externalClassLoader.getResourceAsStream( path.substring(1) );
  198. } else
  199. return Interpreter.class.getResourceAsStream( path );
  200. }
  201. /**
  202. Cache info about whether name is a class or not.
  203. @param value
  204. if value is non-null, cache the class
  205. if value is null, set the flag that it is *not* a class to
  206. speed later resolution
  207. */
  208. public void cacheClassInfo( String name, Class value ) {
  209. if ( value != null )
  210. absoluteClassCache.put( name, value );
  211. else
  212. absoluteNonClasses.put( name, NOVALUE );
  213. }
  214. /**
  215. Cache a resolved (possibly overloaded) method based on the
  216. argument types used to invoke it, subject to classloader change.
  217. Static and Object methods are cached separately to support fast lookup
  218. in the general case where either will do.
  219. */
  220. public void cacheResolvedMethod(
  221. Class clas, Object [] args, Method method )
  222. {
  223. if ( Interpreter.DEBUG )
  224. Interpreter.debug(
  225. "cacheResolvedMethod putting: " + clas +" "+ method );
  226. SignatureKey sk = new SignatureKey( clas, method.getName(), args );
  227. if ( Modifier.isStatic( method.getModifiers() ) )
  228. resolvedStaticMethods.put( sk, method );
  229. else
  230. resolvedObjectMethods.put( sk, method );
  231. }
  232. /**
  233. Return a previously cached resolved method.
  234. @param onlyStatic specifies that only a static method may be returned.
  235. @return the Method or null
  236. */
  237. public Method getResolvedMethod(
  238. Class clas, String methodName, Object [] args, boolean onlyStatic )
  239. {
  240. SignatureKey sk = new SignatureKey( clas, methodName, args );
  241. // Try static and then object, if allowed
  242. // Note that the Java compiler should not allow both.
  243. Method method = (Method)resolvedStaticMethods.get( sk );
  244. if ( method == null && !onlyStatic)
  245. method = (Method)resolvedObjectMethods.get( sk );
  246. if ( Interpreter.DEBUG )
  247. {
  248. if ( method == null )
  249. Interpreter.debug(
  250. "getResolvedMethod cache MISS: " + clas +" - "+methodName );
  251. else
  252. Interpreter.debug(
  253. "getResolvedMethod cache HIT: " + clas +" - " +method );
  254. }
  255. return method;
  256. }
  257. /**
  258. Clear the caches in BshClassManager
  259. @see public void #reset() for external usage
  260. */
  261. protected void clearCaches()
  262. {
  263. absoluteNonClasses = new Hashtable();
  264. absoluteClassCache = new Hashtable();
  265. resolvedObjectMethods = new Hashtable();
  266. resolvedStaticMethods = new Hashtable();
  267. }
  268. /**
  269. Set an external class loader. BeanShell will use this at the same
  270. point it would otherwise use the plain Class.forName().
  271. i.e. if no explicit classpath management is done from the script
  272. (addClassPath(), setClassPath(), reloadClasses()) then BeanShell will
  273. only use the supplied classloader. If additional classpath management
  274. is done then BeanShell will perform that in addition to the supplied
  275. external classloader.
  276. However BeanShell is not currently able to reload
  277. classes supplied through the external classloader.
  278. */
  279. public void setClassLoader( ClassLoader externalCL )
  280. {
  281. externalClassLoader = externalCL;
  282. classLoaderChanged();
  283. }
  284. public void addClassPath( URL path )
  285. throws IOException {
  286. }
  287. /**
  288. Clear all loaders and start over. No class loading.
  289. */
  290. public void reset() {
  291. clearCaches();
  292. }
  293. /**
  294. Set a new base classpath and create a new base classloader.
  295. This means all types change.
  296. */
  297. public void setClassPath( URL [] cp )
  298. throws UtilEvalError
  299. {
  300. throw cmUnavailable();
  301. }
  302. /**
  303. Overlay the entire path with a new class loader.
  304. Set the base path to the user path + base path.
  305. No point in including the boot class path (can't reload thos).
  306. */
  307. public void reloadAllClasses() throws UtilEvalError {
  308. throw cmUnavailable();
  309. }
  310. /**
  311. Reloading classes means creating a new classloader and using it
  312. whenever we are asked for classes in the appropriate space.
  313. For this we use a DiscreteFilesClassLoader
  314. */
  315. public void reloadClasses( String [] classNames )
  316. throws UtilEvalError
  317. {
  318. throw cmUnavailable();
  319. }
  320. /**
  321. Reload all classes in the specified package: e.g. "com.sun.tools"
  322. The special package name "<unpackaged>" can be used to refer
  323. to unpackaged classes.
  324. */
  325. public void reloadPackage( String pack )
  326. throws UtilEvalError
  327. {
  328. throw cmUnavailable();
  329. }
  330. /**
  331. This has been removed from the interface to shield the core from the
  332. rest of the classpath package. If you need the classpath you will have
  333. to cast the classmanager to its impl.
  334. public BshClassPath getClassPath() throws ClassPathException;
  335. */
  336. /**
  337. Support for "import *;"
  338. Hide details in here as opposed to NameSpace.
  339. */
  340. protected void doSuperImport()
  341. throws UtilEvalError
  342. {
  343. throw cmUnavailable();
  344. }
  345. /**
  346. A "super import" ("import *") operation has been performed.
  347. */
  348. protected boolean hasSuperImport()
  349. {
  350. return false;
  351. }
  352. /**
  353. Return the name or null if none is found,
  354. Throw an ClassPathException containing detail if name is ambigous.
  355. */
  356. protected String getClassNameByUnqName( String name )
  357. throws UtilEvalError
  358. {
  359. throw cmUnavailable();
  360. }
  361. public void addListener( Listener l ) { }
  362. public void removeListener( Listener l ) { }
  363. public void dump( PrintWriter pw ) {
  364. pw.println("BshClassManager: no class manager.");
  365. }
  366. protected void classLoaderChanged() { }
  367. /**
  368. Annotate the NoClassDefFoundError with some info about the class
  369. we were trying to load.
  370. */
  371. protected static Error noClassDefFound( String className, Error e ) {
  372. return new NoClassDefFoundError(
  373. "A class required by class: "+className +" could not be loaded:\n"
  374. +e.toString() );
  375. }
  376. protected static UtilEvalError cmUnavailable() {
  377. return new Capabilities.Unavailable(
  378. "ClassLoading features unavailable.");
  379. }
  380. public static interface Listener
  381. {
  382. public void classLoaderChanged();
  383. }
  384. /**
  385. SignatureKey serves as a hash of a method signature on a class
  386. for fast lookup of overloaded and general resolved Java methods.
  387. <p>
  388. */
  389. /*
  390. Note: is using SignatureKey in this way dangerous? In the pathological
  391. case a user could eat up memory caching every possible combination of
  392. argument types to an untyped method. Maybe we could be smarter about
  393. it by ignoring the types of untyped parameter positions? The method
  394. resolver could return a set of "hints" for the signature key caching?
  395. There is also the overhead of creating one of these for every method
  396. dispatched. What is the alternative?
  397. */
  398. static class SignatureKey
  399. {
  400. Class clas;
  401. Class [] types;
  402. String methodName;
  403. int hashCode = 0;
  404. SignatureKey( Class clas, String methodName, Object [] args ) {
  405. this.clas = clas;
  406. this.methodName = methodName;
  407. this.types = Reflect.getTypes( args );
  408. }
  409. public int hashCode()
  410. {
  411. if ( hashCode == 0 )
  412. {
  413. hashCode = clas.hashCode() * methodName.hashCode();
  414. if ( types == null ) // no args method
  415. return hashCode;
  416. for( int i =0; i < types.length; i++ ) {
  417. int hc = types[i] == null ? 21 : types[i].hashCode();
  418. hashCode = hashCode*(i+1) + hc;
  419. }
  420. }
  421. return hashCode;
  422. }
  423. public boolean equals( Object o ) {
  424. SignatureKey target = (SignatureKey)o;
  425. if ( types == null )
  426. return target.types == null;
  427. if ( clas != target.clas )
  428. return false;
  429. if ( !methodName.equals( target.methodName ) )
  430. return false;
  431. if ( types.length != target.types.length )
  432. return false;
  433. for( int i =0; i< types.length; i++ )
  434. {
  435. if ( types[i]==null )
  436. {
  437. if ( !(target.types[i]==null) )
  438. return false;
  439. } else
  440. if ( !types[i].equals( target.types[i] ) )
  441. return false;
  442. }
  443. return true;
  444. }
  445. }
  446. }