You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ClassPool.java 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711
  1. /*
  2. * Javassist, a Java-bytecode translator toolkit.
  3. * Copyright (C) 1999-2004 Shigeru Chiba. All Rights Reserved.
  4. *
  5. * The contents of this file are subject to the Mozilla Public License Version
  6. * 1.1 (the "License"); you may not use this file except in compliance with
  7. * the License. Alternatively, the contents of this file may be used under
  8. * the terms of the GNU Lesser General Public License Version 2.1 or later.
  9. *
  10. * Software distributed under the License is distributed on an "AS IS" basis,
  11. * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  12. * for the specific language governing rights and limitations under the
  13. * License.
  14. */
  15. package javassist;
  16. import java.io.*;
  17. import java.net.URL;
  18. import java.util.Hashtable;
  19. /**
  20. * A container of <code>CtClass</code> objects.
  21. * A <code>CtClass</code> object must be obtained from this object.
  22. * If <code>get()</code> is called on this object,
  23. * it searches various sources represented by <code>ClassPath</code>
  24. * to find a class file and then it creates a <code>CtClass</code> object
  25. * representing that class file. The created object is returned to the
  26. * caller.
  27. *
  28. * <p><b>Memory consumption memo:</b>
  29. *
  30. * <p><code>ClassPool</code> objects hold all the <code>CtClass</code>es
  31. * that have been created so that the consistency among modified classes
  32. * can be guaranteed. Thus if a large number of <code>CtClass</code>es
  33. * are processed, the <code>ClassPool</code> will consume a huge amount
  34. * of memory. To avoid this, a <code>ClassPool</code> object
  35. * should be recreated, for example, every hundred classes processed.
  36. * Note that <code>getDefault()</code> is a singleton factory.
  37. *
  38. * <p><b><code>ClassPool</code> hierarchy:</b>
  39. *
  40. * <p><code>ClassPool</code>s can make a parent-child hierarchy as
  41. * <code>java.lang.ClassLoader</code>s. If a <code>ClassPool</code> has
  42. * a parent pool, <code>get()</code> first asks the parent pool to find
  43. * a class file. Only if the parent could not find the class file,
  44. * <code>get()</code> searches the <code>ClassPath</code>s of
  45. * the child <code>ClassPool</code>. This search order is reversed if
  46. * <code>ClassPath.childFirstLookup</code> is <code>true</code>.
  47. *
  48. * @see javassist.CtClass
  49. * @see javassist.ClassPath
  50. */
  51. public class ClassPool {
  52. /**
  53. * Determines the search order.
  54. *
  55. * <p>If this field is true, <code>get()</code> first searches the
  56. * class path associated to this <code>ClassPool</code> and then
  57. * the class path associated with the parent <code>ClassPool</code>.
  58. * Otherwise, the class path associated with the parent is searched
  59. * first.
  60. *
  61. * <p>The default value is false.
  62. */
  63. public boolean childFirstLookup = false;
  64. protected ClassPoolTail source;
  65. protected ClassPool parent;
  66. protected Hashtable classes; // should be synchronous
  67. /**
  68. * Table of registered cflow variables.
  69. */
  70. private Hashtable cflow = null; // should be synchronous.
  71. /**
  72. * Creates a root class pool. No parent class pool is specified.
  73. *
  74. */
  75. public ClassPool() {
  76. this(null);
  77. }
  78. /**
  79. * Creates a class pool.
  80. *
  81. * @param parent the parent of this class pool. If this is a root
  82. * class pool, this parameter must be <code>null</code>.
  83. * @see javassist.ClassPool#getDefault()
  84. */
  85. public ClassPool(ClassPool parent) {
  86. this.classes = new Hashtable();
  87. this.source = new ClassPoolTail();
  88. this.parent = parent;
  89. if (parent == null) {
  90. CtClass[] pt = CtClass.primitiveTypes;
  91. for (int i = 0; i < pt.length; ++i)
  92. classes.put(pt[i].getName(), pt[i]);
  93. }
  94. this.cflow = null;
  95. }
  96. /**
  97. * Returns the default class pool.
  98. * The returned object is always identical since this method is
  99. * a singleton factory.
  100. *
  101. * <p>The default class pool searches the system search path,
  102. * which usually includes the platform library, extension
  103. * libraries, and the search path specified by the
  104. * <code>-classpath</code> option or the <code>CLASSPATH</code>
  105. * environment variable.
  106. *
  107. * <p>When this method is called for the first time, the default
  108. * class pool is created with the following code snippet:
  109. *
  110. * <ul><code>ClassPool cp = new ClassPool();
  111. * cp.appendSystemPath();
  112. * </code></ul>
  113. *
  114. * <p>If the default class pool cannot find any class files,
  115. * try <code>ClassClassPath</code> and <code>LoaderClassPath</code>.
  116. *
  117. * @see ClassClassPath
  118. * @see LoaderClassPath
  119. */
  120. public static synchronized ClassPool getDefault() {
  121. if (defaultPool == null) {
  122. defaultPool = new ClassPool(null);
  123. defaultPool.appendSystemPath();
  124. }
  125. return defaultPool;
  126. }
  127. private static ClassPool defaultPool = null;
  128. /**
  129. * Provide a hook so that subclasses can do their own
  130. * caching of classes.
  131. *
  132. * @see #cacheCtClass(String,CtClass)
  133. * @see #removeCached(String)
  134. */
  135. protected CtClass getCached(String classname) {
  136. return (CtClass)classes.get(classname);
  137. }
  138. /**
  139. * Provides a hook so that subclasses can do their own
  140. * caching of classes.
  141. *
  142. * @see #getCached(String)
  143. * @see #removeCached(String,CtClass)
  144. */
  145. protected void cacheCtClass(String classname, CtClass c) {
  146. classes.put(classname, c);
  147. }
  148. /**
  149. * Provide a hook so that subclasses can do their own
  150. * caching of classes.
  151. *
  152. * @see #getCached(String)
  153. * @see #cacheCtClass(String,CtClass)
  154. */
  155. protected void removeCached(String classname) {
  156. classes.remove(classname);
  157. }
  158. /**
  159. * Returns the class search path.
  160. */
  161. public String toString() {
  162. return source.toString();
  163. }
  164. /**
  165. * Records a name that never exists.
  166. * For example, a package name can be recorded by this method.
  167. * This would improve execution performance
  168. * since <code>get()</code> does not search the class path at all
  169. * if the given name is an invalid name recorded by this method.
  170. * Note that searching the class path takes relatively long time.
  171. *
  172. * @param name a class name (separeted by dot).
  173. */
  174. public void recordInvalidClassName(String name) {
  175. source.recordInvalidClassName(name);
  176. }
  177. /**
  178. * Records the <code>$cflow</code> variable for the field specified
  179. * by <code>cname</code> and <code>fname</code>.
  180. *
  181. * @param name variable name
  182. * @param cname class name
  183. * @param fname field name
  184. */
  185. void recordCflow(String name, String cname, String fname) {
  186. if (cflow == null)
  187. cflow = new Hashtable();
  188. cflow.put(name, new Object[] { cname, fname });
  189. }
  190. /**
  191. * Undocumented method. Do not use; internal-use only.
  192. *
  193. * @param name the name of <code>$cflow</code> variable
  194. */
  195. public Object[] lookupCflow(String name) {
  196. if (cflow == null)
  197. cflow = new Hashtable();
  198. return (Object[])cflow.get(name);
  199. }
  200. /**
  201. * A simple class loader used by <code>toClass()</code>
  202. * in <code>CtClass</code>.
  203. * This class loader is provided for convenience. If you need more
  204. * complex functionality, you should write your own class loader.
  205. *
  206. * @see CtClass#forName(String)
  207. * @see CtClass#toClass()
  208. * @see #toClass()
  209. * @see #forName(String)
  210. */
  211. public static class SimpleLoader extends ClassLoader {
  212. /**
  213. * Loads a class.
  214. *
  215. * @param name the fully qualified class name.
  216. * @param classfile the class file.
  217. * @throws ClassFormatError if the class file is wrong.
  218. */
  219. public Class loadClass(String name, byte[] classfile)
  220. throws ClassFormatError
  221. {
  222. Class c = defineClass(name, classfile, 0, classfile.length);
  223. resolveClass(c);
  224. return c;
  225. }
  226. };
  227. private static SimpleLoader classLoader = null;
  228. /**
  229. * Returns a <code>java.lang.Class</code> object that has been loaded
  230. * by <code>toClass()</code> in <code>CtClass</code>
  231. * or <code>ClassPool</code>. Such an object cannot be
  232. * obtained by <code>java.lang.Class.forName()</code> because it has
  233. * been loaded by an internal class loader of Javassist.
  234. *
  235. * @param name the fully-qualified class name.
  236. * @see #toClass(CtClass)
  237. */
  238. public Class forName(String name) throws ClassNotFoundException {
  239. if (classLoader == null)
  240. classLoader = new SimpleLoader();
  241. return classLoader.loadClass(name);
  242. }
  243. /**
  244. * Loads the class represented by a <code>CtClass</code> object.
  245. * <code>toClass()</code> in <code>CtClass</code> calls this method
  246. * to load a class.
  247. *
  248. * <p>This method can be overridden to change the class loader.
  249. * In the default implementation,
  250. * the class loader is a <code>SimpleLoader</code>.
  251. * If this method is overridden, <code>forName()</code> must be also
  252. * overridden for extending the behavior.
  253. *
  254. * @param cc the loaded <code>CtClass</code>.
  255. * @return the <code>java.lang.Class</code> object representing
  256. * the loaded class.
  257. * @see #forName(String)
  258. */
  259. public Class toClass(CtClass cc)
  260. throws NotFoundException, CannotCompileException, IOException
  261. {
  262. try {
  263. if (classLoader == null)
  264. classLoader = new SimpleLoader();
  265. return classLoader.loadClass(cc.getName(), cc.toBytecode());
  266. }
  267. catch (ClassFormatError e) {
  268. throw new CannotCompileException(e, cc.getName());
  269. }
  270. }
  271. /**
  272. * Reads a class file and constructs a <code>CtClass</code>
  273. * object with a new name.
  274. * This method is useful if you want to generate a new class as a copy
  275. * of another class (except the class name). For example,
  276. *
  277. * <ul><pre>
  278. * getAndRename("Point", "Pair")
  279. * </pre></ul>
  280. *
  281. * returns a <code>CtClass</code> object representing <code>Pair</code>
  282. * class. The definition of <code>Pair</code> is the same as that of
  283. * <code>Point</code> class except the class name since <code>Pair</code>
  284. * is defined by reading <code>Point.class</code>.
  285. *
  286. * @param orgName the original (fully-qualified) class name
  287. * @param newName the new class name
  288. */
  289. public CtClass getAndRename(String orgName, String newName)
  290. throws NotFoundException
  291. {
  292. CtClass clazz = get0(orgName, false);
  293. if (clazz instanceof CtClassType)
  294. ((CtClassType)clazz).setClassPool(this);
  295. clazz.setName(newName); // indirectly calls
  296. // classNameChanged() in this class
  297. return clazz;
  298. }
  299. /*
  300. * This method is invoked by CtClassType.setName(). It removes a
  301. * CtClass object from the hash table and inserts it with the new
  302. * name. Don't delegate to the parent.
  303. */
  304. synchronized void classNameChanged(String oldname, CtClass clazz) {
  305. CtClass c = (CtClass)getCached(oldname);
  306. if (c == clazz) // must check this equation.
  307. removeCached(oldname); // see getAndRename().
  308. String newName = clazz.getName();
  309. checkNotFrozen(newName);
  310. cacheCtClass(newName, clazz);
  311. }
  312. /**
  313. * Reads a class file from the source and returns a reference
  314. * to the <code>CtClass</code>
  315. * object representing that class file. If that class file has been
  316. * already read, this method returns a reference to the
  317. * <code>CtClass</code> created when that class file was read at the
  318. * first time.
  319. *
  320. * <p>If <code>classname</code> ends with "[]", then this method
  321. * returns a <code>CtClass</code> object for that array type.
  322. *
  323. * <p>To obtain an inner class, use "$" instead of "." for separating
  324. * the enclosing class name and the inner class name.
  325. *
  326. * @param classname a fully-qualified class name.
  327. */
  328. public CtClass get(String classname) throws NotFoundException {
  329. CtClass clazz = get0(classname, true);
  330. if (clazz == null)
  331. throw new NotFoundException(classname);
  332. else
  333. return clazz;
  334. }
  335. /**
  336. * @param useCache false if the cached CtClass must be ignored.
  337. * @param searchParent false if the parent class pool is not searched.
  338. * @return null if the class could not be found.
  339. */
  340. protected synchronized CtClass get0(String classname, boolean useCache)
  341. throws NotFoundException
  342. {
  343. CtClass clazz = null;
  344. if (useCache) {
  345. clazz = getCached(classname);
  346. if (clazz != null)
  347. return clazz;
  348. }
  349. if (!childFirstLookup && parent != null) {
  350. clazz = parent.get0(classname, useCache);
  351. if (clazz != null)
  352. return clazz;
  353. }
  354. clazz = createCtClass(classname, useCache);
  355. if (clazz != null) {
  356. if (useCache)
  357. cacheCtClass(classname, clazz);
  358. return clazz;
  359. }
  360. if (childFirstLookup && parent != null)
  361. clazz = parent.get0(classname, useCache);
  362. return clazz;
  363. }
  364. /**
  365. * Creates a CtClass object representing the specified class.
  366. * It first examines whether or not the corresponding class
  367. * file exists. If yes, it creates a CtClass object.
  368. *
  369. * @return null if the class file could not be found.
  370. */
  371. protected CtClass createCtClass(String classname, boolean useCache) {
  372. if (classname.endsWith("[]")) {
  373. String base = classname.substring(0, classname.indexOf('['));
  374. if ((!useCache || getCached(base) == null) && find(base) == null)
  375. return null;
  376. else
  377. return new CtArray(classname, this);
  378. }
  379. else
  380. if (find(classname) == null)
  381. return null;
  382. else
  383. return new CtClassType(classname, this);
  384. }
  385. /**
  386. * Searches the class path to obtain the URL of the class file
  387. * specified by classname. It is also used to determine whether
  388. * the class file exists.
  389. *
  390. * @param classname a fully-qualified class name.
  391. * @return null if the class file could not be found.
  392. * @see CtClassType#getURL()
  393. */
  394. public URL find(String classname) {
  395. return source.find(classname);
  396. }
  397. /*
  398. * Is invoked by CtClassType.setName() and methods in this class.
  399. * This method throws an exception if the class is already frozen or
  400. * if this class pool cannot edit the class since it is in a parent
  401. * class pool.
  402. */
  403. void checkNotFrozen(String classname) throws RuntimeException {
  404. CtClass clazz = getCached(classname);
  405. if (clazz == null) {
  406. if (!childFirstLookup && parent != null) {
  407. try {
  408. clazz = parent.get0(classname, true);
  409. }
  410. catch (NotFoundException e) {}
  411. if (clazz != null)
  412. throw new RuntimeException(classname
  413. + " is in a parent ClassPool. Use the parent.");
  414. }
  415. }
  416. else
  417. if (clazz.isFrozen())
  418. throw new RuntimeException(classname +
  419. ": frozen class (cannot edit)");
  420. }
  421. /* for CtClassType.getClassFile2(). Don't delegate to the parent.
  422. */
  423. InputStream openClassfile(String classname)
  424. throws NotFoundException
  425. {
  426. return source.openClassfile(classname);
  427. }
  428. void writeClassfile(String classname, OutputStream out)
  429. throws NotFoundException, IOException, CannotCompileException
  430. {
  431. source.writeClassfile(classname, out);
  432. }
  433. /**
  434. * Reads class files from the source and returns an array of
  435. * <code>CtClass</code>
  436. * objects representing those class files.
  437. *
  438. * <p>If an element of <code>classnames</code> ends with "[]",
  439. * then this method
  440. * returns a <code>CtClass</code> object for that array type.
  441. *
  442. * @param classnames an array of fully-qualified class name.
  443. */
  444. public CtClass[] get(String[] classnames) throws NotFoundException {
  445. if (classnames == null)
  446. return new CtClass[0];
  447. int num = classnames.length;
  448. CtClass[] result = new CtClass[num];
  449. for (int i = 0; i < num; ++i)
  450. result[i] = get(classnames[i]);
  451. return result;
  452. }
  453. /**
  454. * Reads a class file and obtains a compile-time method.
  455. *
  456. * @param classname the class name
  457. * @param methodname the method name
  458. *
  459. * @see CtClass#getDeclaredMethod(String)
  460. */
  461. public CtMethod getMethod(String classname, String methodname)
  462. throws NotFoundException
  463. {
  464. CtClass c = get(classname);
  465. return c.getDeclaredMethod(methodname);
  466. }
  467. /**
  468. * Creates a new class (or interface) from the given class file.
  469. * If there already exists a class with the same name, the new class
  470. * overwrites that previous class.
  471. *
  472. * <p>This method is used for creating a <code>CtClass</code> object
  473. * directly from a class file. The qualified class name is obtained
  474. * from the class file; you do not have to explicitly give the name.
  475. *
  476. * @param classfile class file.
  477. * @exception RuntimeException if there is a frozen class with the
  478. * the same name.
  479. * @see javassist.ByteArrayClassPath
  480. */
  481. public CtClass makeClass(InputStream classfile)
  482. throws IOException, RuntimeException
  483. {
  484. classfile = new BufferedInputStream(classfile);
  485. CtClass clazz = new CtClassType(classfile, this);
  486. clazz.checkModify();
  487. String classname = clazz.getName();
  488. checkNotFrozen(classname);
  489. cacheCtClass(classname, clazz);
  490. return clazz;
  491. }
  492. /**
  493. * Creates a new public class.
  494. * If there already exists a class with the same name, the new class
  495. * overwrites that previous class.
  496. *
  497. * @param classname a fully-qualified class name.
  498. * @exception RuntimeException if the existing class is frozen.
  499. */
  500. public CtClass makeClass(String classname) throws RuntimeException {
  501. return makeClass(classname, null);
  502. }
  503. /**
  504. * Creates a new public class.
  505. * If there already exists a class/interface with the same name,
  506. * the new class overwrites that previous class.
  507. *
  508. * @param classname a fully-qualified class name.
  509. * @param superclass the super class.
  510. * @exception RuntimeException if the existing class is frozen.
  511. */
  512. public synchronized CtClass makeClass(String classname, CtClass superclass)
  513. throws RuntimeException
  514. {
  515. checkNotFrozen(classname);
  516. CtClass clazz = new CtNewClass(classname, this, false, superclass);
  517. cacheCtClass(classname, clazz);
  518. return clazz;
  519. }
  520. /**
  521. * Creates a new public interface.
  522. * If there already exists a class/interface with the same name,
  523. * the new interface overwrites that previous one.
  524. *
  525. * @param name a fully-qualified interface name.
  526. * @exception RuntimeException if the existing interface is frozen.
  527. */
  528. public CtClass makeInterface(String name) throws RuntimeException {
  529. return makeInterface(name, null);
  530. }
  531. /**
  532. * Creates a new public interface.
  533. * If there already exists a class/interface with the same name,
  534. * the new interface overwrites that previous one.
  535. *
  536. * @param name a fully-qualified interface name.
  537. * @param superclass the super interface.
  538. * @exception RuntimeException if the existing interface is frozen.
  539. */
  540. public synchronized CtClass makeInterface(String name, CtClass superclass)
  541. throws RuntimeException
  542. {
  543. checkNotFrozen(name);
  544. CtClass clazz = new CtNewClass(name, this, true, superclass);
  545. cacheCtClass(name, clazz);
  546. return clazz;
  547. }
  548. /**
  549. * Appends the system search path to the end of the
  550. * search path. The system search path
  551. * usually includes the platform library, extension
  552. * libraries, and the search path specified by the
  553. * <code>-classpath</code> option or the <code>CLASSPATH</code>
  554. * environment variable.
  555. *
  556. * @return the appended class path.
  557. */
  558. public ClassPath appendSystemPath() {
  559. return source.appendSystemPath();
  560. }
  561. /**
  562. * Insert a <code>ClassPath</code> object at the head of the
  563. * search path.
  564. *
  565. * @return the inserted class path.
  566. *
  567. * @see javassist.ClassPath
  568. * @see javassist.URLClassPath
  569. * @see javassist.ByteArrayClassPath
  570. */
  571. public ClassPath insertClassPath(ClassPath cp) {
  572. return source.insertClassPath(cp);
  573. }
  574. /**
  575. * Appends a <code>ClassPath</code> object to the end of the
  576. * search path.
  577. *
  578. * @return the appended class path.
  579. *
  580. * @see javassist.ClassPath
  581. * @see javassist.URLClassPath
  582. * @see javassist.ByteArrayClassPath
  583. */
  584. public ClassPath appendClassPath(ClassPath cp) {
  585. return source.appendClassPath(cp);
  586. }
  587. /**
  588. * Inserts a directory or a jar (or zip) file at the head of the
  589. * search path.
  590. *
  591. * @param pathname the path name of the directory or jar file.
  592. * It must not end with a path separator ("/").
  593. * @return the inserted class path.
  594. * @exception NotFoundException if the jar file is not found.
  595. */
  596. public ClassPath insertClassPath(String pathname)
  597. throws NotFoundException
  598. {
  599. return source.insertClassPath(pathname);
  600. }
  601. /**
  602. * Appends a directory or a jar (or zip) file to the end of the
  603. * search path.
  604. *
  605. * @param pathname the path name of the directory or jar file.
  606. * It must not end with a path separator ("/").
  607. * @return the appended class path.
  608. * @exception NotFoundException if the jar file is not found.
  609. */
  610. public ClassPath appendClassPath(String pathname)
  611. throws NotFoundException
  612. {
  613. return source.appendClassPath(pathname);
  614. }
  615. /**
  616. * Detatches the <code>ClassPath</code> object from the search path.
  617. * The detached <code>ClassPath</code> object cannot be added
  618. * to the pathagain.
  619. */
  620. public void removeClassPath(ClassPath cp) {
  621. source.removeClassPath(cp);
  622. }
  623. /**
  624. * Appends directories and jar files for search.
  625. *
  626. * <p>The elements of the given path list must be separated by colons
  627. * in Unix or semi-colons in Windows.
  628. *
  629. * @param pathlist a (semi)colon-separated list of
  630. * the path names of directories and jar files.
  631. * The directory name must not end with a path
  632. * separator ("/").
  633. *
  634. * @exception NotFoundException if a jar file is not found.
  635. */
  636. public void appendPathList(String pathlist) throws NotFoundException {
  637. char sep = File.pathSeparatorChar;
  638. int i = 0;
  639. for (;;) {
  640. int j = pathlist.indexOf(sep, i);
  641. if (j < 0) {
  642. appendClassPath(pathlist.substring(i));
  643. break;
  644. }
  645. else {
  646. appendClassPath(pathlist.substring(i, j));
  647. i = j + 1;
  648. }
  649. }
  650. }
  651. }