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 22KB

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