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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688
  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. */
  209. public static class SimpleLoader extends ClassLoader {
  210. /**
  211. * Loads a class.
  212. *
  213. * @param name the fully qualified class name.
  214. * @param classfile the class file.
  215. * @throws ClassFormatError if the class file is wrong.
  216. */
  217. public Class loadClass(String name, byte[] classfile)
  218. throws ClassFormatError
  219. {
  220. Class c = defineClass(name, classfile, 0, classfile.length);
  221. resolveClass(c);
  222. return c;
  223. }
  224. };
  225. private static SimpleLoader classLoader = null;
  226. /**
  227. * Returns a <code>java.lang.Class</code> object that has been loaded
  228. * by <code>loadClass()</code>. Such an object cannot be
  229. * obtained by <code>java.lang.Class.forName()</code> because it has
  230. * been loaded by an internal class loader of Javassist.
  231. */
  232. static Class forName(String name) throws ClassNotFoundException {
  233. if (classLoader == null)
  234. classLoader = new SimpleLoader();
  235. return classLoader.loadClass(name);
  236. }
  237. static Class loadClass(String classname, byte[] classfile)
  238. throws NotFoundException, IOException, CannotCompileException
  239. {
  240. if (classLoader == null)
  241. classLoader = new SimpleLoader();
  242. try {
  243. return classLoader.loadClass(classname, classfile);
  244. }
  245. catch (ClassFormatError e) {
  246. throw new CannotCompileException(e, classname);
  247. }
  248. }
  249. /**
  250. * Reads a class file and constructs a <code>CtClass</code>
  251. * object with a new name.
  252. * This method is useful if you want to generate a new class as a copy
  253. * of another class (except the class name). For example,
  254. *
  255. * <ul><pre>
  256. * getAndRename("Point", "Pair")
  257. * </pre></ul>
  258. *
  259. * returns a <code>CtClass</code> object representing <code>Pair</code>
  260. * class. The definition of <code>Pair</code> is the same as that of
  261. * <code>Point</code> class except the class name since <code>Pair</code>
  262. * is defined by reading <code>Point.class</code>.
  263. *
  264. * @param orgName the original (fully-qualified) class name
  265. * @param newName the new class name
  266. */
  267. public CtClass getAndRename(String orgName, String newName)
  268. throws NotFoundException
  269. {
  270. CtClass clazz = get0(orgName, false);
  271. if (clazz instanceof CtClassType)
  272. ((CtClassType)clazz).setClassPool(this);
  273. clazz.setName(newName); // indirectly calls
  274. // classNameChanged() in this class
  275. return clazz;
  276. }
  277. /*
  278. * This method is invoked by CtClassType.setName(). It removes a
  279. * CtClass object from the hash table and inserts it with the new
  280. * name. Don't delegate to the parent.
  281. */
  282. synchronized void classNameChanged(String oldname, CtClass clazz) {
  283. CtClass c = (CtClass)getCached(oldname);
  284. if (c == clazz) // must check this equation.
  285. removeCached(oldname); // see getAndRename().
  286. String newName = clazz.getName();
  287. checkNotFrozen(newName);
  288. cacheCtClass(newName, clazz);
  289. }
  290. /**
  291. * Reads a class file from the source and returns a reference
  292. * to the <code>CtClass</code>
  293. * object representing that class file. If that class file has been
  294. * already read, this method returns a reference to the
  295. * <code>CtClass</code> created when that class file was read at the
  296. * first time.
  297. *
  298. * <p>If <code>classname</code> ends with "[]", then this method
  299. * returns a <code>CtClass</code> object for that array type.
  300. *
  301. * <p>To obtain an inner class, use "$" instead of "." for separating
  302. * the enclosing class name and the inner class name.
  303. *
  304. * @param classname a fully-qualified class name.
  305. */
  306. public CtClass get(String classname) throws NotFoundException {
  307. CtClass clazz = get0(classname, true);
  308. if (clazz == null)
  309. throw new NotFoundException(classname);
  310. else
  311. return clazz;
  312. }
  313. /**
  314. * @param useCache false if the cached CtClass must be ignored.
  315. * @param searchParent false if the parent class pool is not searched.
  316. * @return null if the class could not be found.
  317. */
  318. protected synchronized CtClass get0(String classname, boolean useCache)
  319. throws NotFoundException
  320. {
  321. CtClass clazz = null;
  322. if (useCache) {
  323. clazz = getCached(classname);
  324. if (clazz != null)
  325. return clazz;
  326. }
  327. if (!childFirstLookup && parent != null) {
  328. clazz = parent.get0(classname, useCache);
  329. if (clazz != null)
  330. return clazz;
  331. }
  332. clazz = createCtClass(classname, useCache);
  333. if (clazz != null) {
  334. if (useCache)
  335. cacheCtClass(classname, clazz);
  336. return clazz;
  337. }
  338. if (childFirstLookup && parent != null)
  339. clazz = parent.get0(classname, useCache);
  340. return clazz;
  341. }
  342. /**
  343. * Creates a CtClass object representing the specified class.
  344. * It first examines whether or not the corresponding class
  345. * file exists. If yes, it creates a CtClass object.
  346. *
  347. * @return null if the class file could not be found.
  348. */
  349. protected CtClass createCtClass(String classname, boolean useCache) {
  350. if (classname.endsWith("[]")) {
  351. String base = classname.substring(0, classname.indexOf('['));
  352. if ((!useCache || getCached(base) == null) && find(base) == null)
  353. return null;
  354. else
  355. return new CtArray(classname, this);
  356. }
  357. else
  358. if (find(classname) == null)
  359. return null;
  360. else
  361. return new CtClassType(classname, this);
  362. }
  363. /**
  364. * Searches the class path to obtain the URL of the class file
  365. * specified by classname. It is also used to determine whether
  366. * the class file exists.
  367. *
  368. * @param classname a fully-qualified class name.
  369. * @return null if the class file could not be found.
  370. * @see CtClassType#getURL()
  371. */
  372. public URL find(String classname) {
  373. return source.find(classname);
  374. }
  375. /*
  376. * Is invoked by CtClassType.setName() and methods in this class.
  377. * This method throws an exception if the class is already frozen or
  378. * if this class pool cannot edit the class since it is in a parent
  379. * class pool.
  380. */
  381. void checkNotFrozen(String classname) throws RuntimeException {
  382. CtClass clazz = getCached(classname);
  383. if (clazz == null) {
  384. if (!childFirstLookup && parent != null) {
  385. try {
  386. clazz = parent.get0(classname, true);
  387. }
  388. catch (NotFoundException e) {}
  389. if (clazz != null)
  390. throw new RuntimeException(classname
  391. + " is in a parent ClassPool. Use the parent.");
  392. }
  393. }
  394. else
  395. if (clazz.isFrozen())
  396. throw new RuntimeException(classname +
  397. ": frozen class (cannot edit)");
  398. }
  399. /* for CtClassType.getClassFile2(). Don't delegate to the parent.
  400. */
  401. InputStream openClassfile(String classname)
  402. throws NotFoundException
  403. {
  404. return source.openClassfile(classname);
  405. }
  406. void writeClassfile(String classname, OutputStream out)
  407. throws NotFoundException, IOException, CannotCompileException
  408. {
  409. source.writeClassfile(classname, out);
  410. }
  411. /**
  412. * Reads class files from the source and returns an array of
  413. * <code>CtClass</code>
  414. * objects representing those class files.
  415. *
  416. * <p>If an element of <code>classnames</code> ends with "[]",
  417. * then this method
  418. * returns a <code>CtClass</code> object for that array type.
  419. *
  420. * @param classnames an array of fully-qualified class name.
  421. */
  422. public CtClass[] get(String[] classnames) throws NotFoundException {
  423. if (classnames == null)
  424. return new CtClass[0];
  425. int num = classnames.length;
  426. CtClass[] result = new CtClass[num];
  427. for (int i = 0; i < num; ++i)
  428. result[i] = get(classnames[i]);
  429. return result;
  430. }
  431. /**
  432. * Reads a class file and obtains a compile-time method.
  433. *
  434. * @param classname the class name
  435. * @param methodname the method name
  436. *
  437. * @see CtClass#getDeclaredMethod(String)
  438. */
  439. public CtMethod getMethod(String classname, String methodname)
  440. throws NotFoundException
  441. {
  442. CtClass c = get(classname);
  443. return c.getDeclaredMethod(methodname);
  444. }
  445. /**
  446. * Creates a new class (or interface) from the given class file.
  447. * If there already exists a class with the same name, the new class
  448. * overwrites that previous class.
  449. *
  450. * <p>This method is used for creating a <code>CtClass</code> object
  451. * directly from a class file. The qualified class name is obtained
  452. * from the class file; you do not have to explicitly give the name.
  453. *
  454. * @param classfile class file.
  455. * @exception RuntimeException if there is a frozen class with the
  456. * the same name.
  457. * @see javassist.ByteArrayClassPath
  458. */
  459. public CtClass makeClass(InputStream classfile)
  460. throws IOException, RuntimeException
  461. {
  462. CtClass clazz = new CtClassType(classfile, this);
  463. clazz.checkModify();
  464. String classname = clazz.getName();
  465. checkNotFrozen(classname);
  466. cacheCtClass(classname, clazz);
  467. return clazz;
  468. }
  469. /**
  470. * Creates a new public class.
  471. * If there already exists a class with the same name, the new class
  472. * overwrites that previous class.
  473. *
  474. * @param classname a fully-qualified class name.
  475. * @exception RuntimeException if the existing class is frozen.
  476. */
  477. public CtClass makeClass(String classname) throws RuntimeException {
  478. return makeClass(classname, null);
  479. }
  480. /**
  481. * Creates a new public class.
  482. * If there already exists a class/interface with the same name,
  483. * the new class overwrites that previous class.
  484. *
  485. * @param classname a fully-qualified class name.
  486. * @param superclass the super class.
  487. * @exception RuntimeException if the existing class is frozen.
  488. */
  489. public synchronized CtClass makeClass(String classname, CtClass superclass)
  490. throws RuntimeException
  491. {
  492. checkNotFrozen(classname);
  493. CtClass clazz = new CtNewClass(classname, this, false, superclass);
  494. cacheCtClass(classname, clazz);
  495. return clazz;
  496. }
  497. /**
  498. * Creates a new public interface.
  499. * If there already exists a class/interface with the same name,
  500. * the new interface overwrites that previous one.
  501. *
  502. * @param name a fully-qualified interface name.
  503. * @exception RuntimeException if the existing interface is frozen.
  504. */
  505. public CtClass makeInterface(String name) throws RuntimeException {
  506. return makeInterface(name, null);
  507. }
  508. /**
  509. * Creates a new public interface.
  510. * If there already exists a class/interface with the same name,
  511. * the new interface overwrites that previous one.
  512. *
  513. * @param name a fully-qualified interface name.
  514. * @param superclass the super interface.
  515. * @exception RuntimeException if the existing interface is frozen.
  516. */
  517. public synchronized CtClass makeInterface(String name, CtClass superclass)
  518. throws RuntimeException
  519. {
  520. checkNotFrozen(name);
  521. CtClass clazz = new CtNewClass(name, this, true, superclass);
  522. cacheCtClass(name, clazz);
  523. return clazz;
  524. }
  525. /**
  526. * Appends the system search path to the end of the
  527. * search path. The system search path
  528. * usually includes the platform library, extension
  529. * libraries, and the search path specified by the
  530. * <code>-classpath</code> option or the <code>CLASSPATH</code>
  531. * environment variable.
  532. *
  533. * @return the appended class path.
  534. */
  535. public ClassPath appendSystemPath() {
  536. return source.appendSystemPath();
  537. }
  538. /**
  539. * Insert a <code>ClassPath</code> object at the head of the
  540. * search path.
  541. *
  542. * @return the inserted class path.
  543. *
  544. * @see javassist.ClassPath
  545. * @see javassist.URLClassPath
  546. * @see javassist.ByteArrayClassPath
  547. */
  548. public ClassPath insertClassPath(ClassPath cp) {
  549. return source.insertClassPath(cp);
  550. }
  551. /**
  552. * Appends a <code>ClassPath</code> object to the end of the
  553. * search path.
  554. *
  555. * @return the appended class path.
  556. *
  557. * @see javassist.ClassPath
  558. * @see javassist.URLClassPath
  559. * @see javassist.ByteArrayClassPath
  560. */
  561. public ClassPath appendClassPath(ClassPath cp) {
  562. return source.appendClassPath(cp);
  563. }
  564. /**
  565. * Inserts a directory or a jar (or zip) file at the head of the
  566. * search path.
  567. *
  568. * @param pathname the path name of the directory or jar file.
  569. * It must not end with a path separator ("/").
  570. * @return the inserted class path.
  571. * @exception NotFoundException if the jar file is not found.
  572. */
  573. public ClassPath insertClassPath(String pathname)
  574. throws NotFoundException
  575. {
  576. return source.insertClassPath(pathname);
  577. }
  578. /**
  579. * Appends a directory or a jar (or zip) file to the end of the
  580. * search path.
  581. *
  582. * @param pathname the path name of the directory or jar file.
  583. * It must not end with a path separator ("/").
  584. * @return the appended class path.
  585. * @exception NotFoundException if the jar file is not found.
  586. */
  587. public ClassPath appendClassPath(String pathname)
  588. throws NotFoundException
  589. {
  590. return source.appendClassPath(pathname);
  591. }
  592. /**
  593. * Detatches the <code>ClassPath</code> object from the search path.
  594. * The detached <code>ClassPath</code> object cannot be added
  595. * to the pathagain.
  596. */
  597. public void removeClassPath(ClassPath cp) {
  598. source.removeClassPath(cp);
  599. }
  600. /**
  601. * Appends directories and jar files for search.
  602. *
  603. * <p>The elements of the given path list must be separated by colons
  604. * in Unix or semi-colons in Windows.
  605. *
  606. * @param pathlist a (semi)colon-separated list of
  607. * the path names of directories and jar files.
  608. * The directory name must not end with a path
  609. * separator ("/").
  610. *
  611. * @exception NotFoundException if a jar file is not found.
  612. */
  613. public void appendPathList(String pathlist) throws NotFoundException {
  614. char sep = File.pathSeparatorChar;
  615. int i = 0;
  616. for (;;) {
  617. int j = pathlist.indexOf(sep, i);
  618. if (j < 0) {
  619. appendClassPath(pathlist.substring(i));
  620. break;
  621. }
  622. else {
  623. appendClassPath(pathlist.substring(i, j));
  624. i = j + 1;
  625. }
  626. }
  627. }
  628. }