Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

ClassPool.java 30KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899
  1. /*
  2. * Javassist, a Java-bytecode translator toolkit.
  3. * Copyright (C) 1999-2006 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.BufferedInputStream;
  17. import java.io.File;
  18. import java.io.IOException;
  19. import java.io.InputStream;
  20. import java.io.OutputStream;
  21. import java.net.URL;
  22. import java.security.ProtectionDomain;
  23. import java.util.Hashtable;
  24. import java.util.Iterator;
  25. import java.util.ArrayList;
  26. import javassist.bytecode.Descriptor;
  27. /**
  28. * A container of <code>CtClass</code> objects.
  29. * A <code>CtClass</code> object must be obtained from this object.
  30. * If <code>get()</code> is called on this object,
  31. * it searches various sources represented by <code>ClassPath</code>
  32. * to find a class file and then it creates a <code>CtClass</code> object
  33. * representing that class file. The created object is returned to the
  34. * caller.
  35. *
  36. * <p><b>Memory consumption memo:</b>
  37. *
  38. * <p><code>ClassPool</code> objects hold all the <code>CtClass</code>es
  39. * that have been created so that the consistency among modified classes
  40. * can be guaranteed. Thus if a large number of <code>CtClass</code>es
  41. * are processed, the <code>ClassPool</code> will consume a huge amount
  42. * of memory. To avoid this, a <code>ClassPool</code> object
  43. * should be recreated, for example, every hundred classes processed.
  44. * Note that <code>getDefault()</code> is a singleton factory.
  45. * Otherwise, <code>detach()</code> in <code>CtClass</code> should be used
  46. * to avoid huge memory consumption.
  47. *
  48. * <p><b><code>ClassPool</code> hierarchy:</b>
  49. *
  50. * <p><code>ClassPool</code>s can make a parent-child hierarchy as
  51. * <code>java.lang.ClassLoader</code>s. If a <code>ClassPool</code> has
  52. * a parent pool, <code>get()</code> first asks the parent pool to find
  53. * a class file. Only if the parent could not find the class file,
  54. * <code>get()</code> searches the <code>ClassPath</code>s of
  55. * the child <code>ClassPool</code>. This search order is reversed if
  56. * <code>ClassPath.childFirstLookup</code> is <code>true</code>.
  57. *
  58. * @see javassist.CtClass
  59. * @see javassist.ClassPath
  60. */
  61. public class ClassPool {
  62. // used by toClass().
  63. private static java.lang.reflect.Method defineClass1, defineClass2;
  64. static {
  65. try {
  66. Class cl = Class.forName("java.lang.ClassLoader");
  67. defineClass1 = cl.getDeclaredMethod("defineClass",
  68. new Class[] { String.class, byte[].class,
  69. int.class, int.class });
  70. defineClass2 = cl.getDeclaredMethod("defineClass",
  71. new Class[] { String.class, byte[].class,
  72. int.class, int.class, ProtectionDomain.class });
  73. }
  74. catch (Exception e) {
  75. throw new RuntimeException("cannot initialize ClassPool");
  76. }
  77. }
  78. /**
  79. * Determines the search order.
  80. *
  81. * <p>If this field is true, <code>get()</code> first searches the
  82. * class path associated to this <code>ClassPool</code> and then
  83. * the class path associated with the parent <code>ClassPool</code>.
  84. * Otherwise, the class path associated with the parent is searched
  85. * first.
  86. *
  87. * <p>The default value is false.
  88. */
  89. public boolean childFirstLookup = false;
  90. /**
  91. * Turning the automatic pruning on/off.
  92. *
  93. * <p>If this field is true, <code>CtClass</code> objects are
  94. * automatically pruned by default when <code>toBytecode()</code> etc.
  95. * are called. The automatic pruning can be turned on/off individually
  96. * for each <code>CtClass</code> object.
  97. *
  98. * <p>The initial value is true.
  99. *
  100. * @see CtClass#prune()
  101. * @see CtClass#stopPruning(boolean)
  102. */
  103. public static boolean doPruning = true;
  104. /* releaseUnmodifiedClassFile was introduced for avoiding a bug
  105. of JBoss AOP. So the value should be true except for JBoss AOP.
  106. */
  107. /**
  108. * If true, unmodified and not-recently-used class files are
  109. * periodically released for saving memory.
  110. *
  111. * <p>The initial value is true.
  112. */
  113. public static boolean releaseUnmodifiedClassFile = true;
  114. protected ClassPoolTail source;
  115. protected ClassPool parent;
  116. protected Hashtable classes; // should be synchronous
  117. /**
  118. * Table of registered cflow variables.
  119. */
  120. private Hashtable cflow = null; // should be synchronous.
  121. private static final int INIT_HASH_SIZE = 191;
  122. private ArrayList importedPackages;
  123. /**
  124. * Creates a root class pool. No parent class pool is specified.
  125. */
  126. public ClassPool() {
  127. this(null);
  128. }
  129. /**
  130. * Creates a root class pool. If <code>useDefaultPath</code> is
  131. * true, <code>appendSystemPath()</code> is called. Otherwise,
  132. * this constructor is equivalent to the constructor taking no
  133. * parameter.
  134. *
  135. * @param useDefaultPath true if the system search path is
  136. * appended.
  137. */
  138. public ClassPool(boolean useDefaultPath) {
  139. this(null);
  140. if (useDefaultPath)
  141. appendSystemPath();
  142. }
  143. /**
  144. * Creates a class pool.
  145. *
  146. * @param parent the parent of this class pool. If this is a root
  147. * class pool, this parameter must be <code>null</code>.
  148. * @see javassist.ClassPool#getDefault()
  149. */
  150. public ClassPool(ClassPool parent) {
  151. this.classes = new Hashtable(INIT_HASH_SIZE);
  152. this.source = new ClassPoolTail();
  153. this.parent = parent;
  154. if (parent == null) {
  155. CtClass[] pt = CtClass.primitiveTypes;
  156. for (int i = 0; i < pt.length; ++i)
  157. classes.put(pt[i].getName(), pt[i]);
  158. }
  159. this.cflow = null;
  160. clearImportedPackages();
  161. }
  162. /**
  163. * Returns the default class pool.
  164. * The returned object is always identical since this method is
  165. * a singleton factory.
  166. *
  167. * <p>The default class pool searches the system search path,
  168. * which usually includes the platform library, extension
  169. * libraries, and the search path specified by the
  170. * <code>-classpath</code> option or the <code>CLASSPATH</code>
  171. * environment variable.
  172. *
  173. * <p>When this method is called for the first time, the default
  174. * class pool is created with the following code snippet:
  175. *
  176. * <ul><code>ClassPool cp = new ClassPool();
  177. * cp.appendSystemPath();
  178. * </code></ul>
  179. *
  180. * <p>If the default class pool cannot find any class files,
  181. * try <code>ClassClassPath</code> and <code>LoaderClassPath</code>.
  182. *
  183. * @see ClassClassPath
  184. * @see LoaderClassPath
  185. */
  186. public static synchronized ClassPool getDefault() {
  187. if (defaultPool == null) {
  188. defaultPool = new ClassPool(null);
  189. defaultPool.appendSystemPath();
  190. }
  191. return defaultPool;
  192. }
  193. private static ClassPool defaultPool = null;
  194. /**
  195. * Provide a hook so that subclasses can do their own
  196. * caching of classes.
  197. *
  198. * @see #cacheCtClass(String,CtClass,boolean)
  199. * @see #removeCached(String)
  200. */
  201. protected CtClass getCached(String classname) {
  202. return (CtClass)classes.get(classname);
  203. }
  204. /**
  205. * Provides a hook so that subclasses can do their own
  206. * caching of classes.
  207. *
  208. * @see #getCached(String)
  209. * @see #removeCached(String,CtClass)
  210. */
  211. protected void cacheCtClass(String classname, CtClass c, boolean dynamic) {
  212. classes.put(classname, c);
  213. }
  214. /**
  215. * Provide a hook so that subclasses can do their own
  216. * caching of classes.
  217. *
  218. * @see #getCached(String)
  219. * @see #cacheCtClass(String,CtClass,boolean)
  220. */
  221. protected CtClass removeCached(String classname) {
  222. return (CtClass)classes.remove(classname);
  223. }
  224. /**
  225. * Returns the class search path.
  226. */
  227. public String toString() {
  228. return source.toString();
  229. }
  230. /**
  231. * Record a package name so that the Javassist compiler searches
  232. * the package to resolve a class name.
  233. * Don't record the <code>java.lang</code> package, which has
  234. * been implicitly recorded by default.
  235. *
  236. * <p>Note that <code>get()</code> in <code>ClassPool</code> does
  237. * not search the recorded package. Only the compiler searches it.
  238. *
  239. * @param packageName the package name.
  240. * It must not include the last '.' (dot).
  241. * For example, "java.util" is valid but "java.util." is wrong.
  242. * @since 3.1
  243. */
  244. public void importPackage(String packageName) {
  245. importedPackages.add(packageName);
  246. }
  247. /**
  248. * Clear all the package names recorded by <code>importPackage()</code>.
  249. * The <code>java.lang</code> package is not removed.
  250. *
  251. * @see #importPackage(String)
  252. * @since 3.1
  253. */
  254. public void clearImportedPackages() {
  255. importedPackages = new ArrayList();
  256. importedPackages.add("java.lang");
  257. }
  258. /**
  259. * Returns all the package names recorded by <code>importPackage()</code>.
  260. *
  261. * @see #importPackage(String)
  262. * @since 3.1
  263. */
  264. public Iterator getImportedPackages() {
  265. return importedPackages.iterator();
  266. }
  267. /**
  268. * Records a name that never exists.
  269. * For example, a package name can be recorded by this method.
  270. * This would improve execution performance
  271. * since <code>get()</code> does not search the class path at all
  272. * if the given name is an invalid name recorded by this method.
  273. * Note that searching the class path takes relatively long time.
  274. *
  275. * @param name a class name (separeted by dot).
  276. */
  277. public void recordInvalidClassName(String name) {
  278. source.recordInvalidClassName(name);
  279. }
  280. /**
  281. * Records the <code>$cflow</code> variable for the field specified
  282. * by <code>cname</code> and <code>fname</code>.
  283. *
  284. * @param name variable name
  285. * @param cname class name
  286. * @param fname field name
  287. */
  288. void recordCflow(String name, String cname, String fname) {
  289. if (cflow == null)
  290. cflow = new Hashtable();
  291. cflow.put(name, new Object[] { cname, fname });
  292. }
  293. /**
  294. * Undocumented method. Do not use; internal-use only.
  295. *
  296. * @param name the name of <code>$cflow</code> variable
  297. */
  298. public Object[] lookupCflow(String name) {
  299. if (cflow == null)
  300. cflow = new Hashtable();
  301. return (Object[])cflow.get(name);
  302. }
  303. /**
  304. * Reads a class file and constructs a <code>CtClass</code>
  305. * object with a new name.
  306. * This method is useful if you want to generate a new class as a copy
  307. * of another class (except the class name). For example,
  308. *
  309. * <ul><pre>
  310. * getAndRename("Point", "Pair")
  311. * </pre></ul>
  312. *
  313. * returns a <code>CtClass</code> object representing <code>Pair</code>
  314. * class. The definition of <code>Pair</code> is the same as that of
  315. * <code>Point</code> class except the class name since <code>Pair</code>
  316. * is defined by reading <code>Point.class</code>.
  317. *
  318. * @param orgName the original (fully-qualified) class name
  319. * @param newName the new class name
  320. */
  321. public CtClass getAndRename(String orgName, String newName)
  322. throws NotFoundException
  323. {
  324. CtClass clazz = get0(orgName, false);
  325. if (clazz == null)
  326. throw new NotFoundException(orgName);
  327. if (clazz instanceof CtClassType)
  328. ((CtClassType)clazz).setClassPool(this);
  329. clazz.setName(newName); // indirectly calls
  330. // classNameChanged() in this class
  331. return clazz;
  332. }
  333. /*
  334. * This method is invoked by CtClassType.setName(). It removes a
  335. * CtClass object from the hash table and inserts it with the new
  336. * name. Don't delegate to the parent.
  337. */
  338. synchronized void classNameChanged(String oldname, CtClass clazz) {
  339. CtClass c = (CtClass)getCached(oldname);
  340. if (c == clazz) // must check this equation.
  341. removeCached(oldname); // see getAndRename().
  342. String newName = clazz.getName();
  343. checkNotFrozen(newName);
  344. cacheCtClass(newName, clazz, false);
  345. }
  346. /**
  347. * Reads a class file from the source and returns a reference
  348. * to the <code>CtClass</code>
  349. * object representing that class file. If that class file has been
  350. * already read, this method returns a reference to the
  351. * <code>CtClass</code> created when that class file was read at the
  352. * first time.
  353. *
  354. * <p>If <code>classname</code> ends with "[]", then this method
  355. * returns a <code>CtClass</code> object for that array type.
  356. *
  357. * <p>To obtain an inner class, use "$" instead of "." for separating
  358. * the enclosing class name and the inner class name.
  359. *
  360. * @param classname a fully-qualified class name.
  361. */
  362. public CtClass get(String classname) throws NotFoundException {
  363. CtClass clazz;
  364. if (classname == null)
  365. clazz = null;
  366. else
  367. clazz = get0(classname, true);
  368. if (clazz == null)
  369. throw new NotFoundException(classname);
  370. else {
  371. clazz.incGetCounter();
  372. return clazz;
  373. }
  374. }
  375. /**
  376. * @param useCache false if the cached CtClass must be ignored.
  377. * @param searchParent false if the parent class pool is not searched.
  378. * @return null if the class could not be found.
  379. */
  380. protected synchronized CtClass get0(String classname, boolean useCache)
  381. throws NotFoundException
  382. {
  383. CtClass clazz = null;
  384. if (useCache) {
  385. clazz = getCached(classname);
  386. if (clazz != null)
  387. return clazz;
  388. }
  389. if (!childFirstLookup && parent != null) {
  390. clazz = parent.get0(classname, useCache);
  391. if (clazz != null)
  392. return clazz;
  393. }
  394. clazz = createCtClass(classname, useCache);
  395. if (clazz != null) {
  396. if (useCache)
  397. cacheCtClass(classname, clazz, false);
  398. return clazz;
  399. }
  400. if (childFirstLookup && parent != null)
  401. clazz = parent.get0(classname, useCache);
  402. return clazz;
  403. }
  404. /**
  405. * Creates a CtClass object representing the specified class.
  406. * It first examines whether or not the corresponding class
  407. * file exists. If yes, it creates a CtClass object.
  408. *
  409. * @return null if the class file could not be found.
  410. */
  411. protected CtClass createCtClass(String classname, boolean useCache) {
  412. // accept "[L<class name>;" as a class name.
  413. if (classname.charAt(0) == '[')
  414. classname = Descriptor.toClassName(classname);
  415. if (classname.endsWith("[]")) {
  416. String base = classname.substring(0, classname.indexOf('['));
  417. if ((!useCache || getCached(base) == null) && find(base) == null)
  418. return null;
  419. else
  420. return new CtArray(classname, this);
  421. }
  422. else
  423. if (find(classname) == null)
  424. return null;
  425. else
  426. return new CtClassType(classname, this);
  427. }
  428. /**
  429. * Searches the class path to obtain the URL of the class file
  430. * specified by classname. It is also used to determine whether
  431. * the class file exists.
  432. *
  433. * @param classname a fully-qualified class name.
  434. * @return null if the class file could not be found.
  435. * @see CtClass#getURL()
  436. */
  437. public URL find(String classname) {
  438. return source.find(classname);
  439. }
  440. /*
  441. * Is invoked by CtClassType.setName() and methods in this class.
  442. * This method throws an exception if the class is already frozen or
  443. * if this class pool cannot edit the class since it is in a parent
  444. * class pool.
  445. */
  446. void checkNotFrozen(String classname) throws RuntimeException {
  447. CtClass clazz = getCached(classname);
  448. if (clazz == null) {
  449. if (!childFirstLookup && parent != null) {
  450. try {
  451. clazz = parent.get0(classname, true);
  452. }
  453. catch (NotFoundException e) {}
  454. if (clazz != null)
  455. throw new RuntimeException(classname
  456. + " is in a parent ClassPool. Use the parent.");
  457. }
  458. }
  459. else
  460. if (clazz.isFrozen())
  461. throw new RuntimeException(classname
  462. + ": frozen class (cannot edit)");
  463. }
  464. /* for CtClassType.getClassFile2(). Don't delegate to the parent.
  465. */
  466. InputStream openClassfile(String classname) throws NotFoundException {
  467. return source.openClassfile(classname);
  468. }
  469. void writeClassfile(String classname, OutputStream out)
  470. throws NotFoundException, IOException, CannotCompileException
  471. {
  472. source.writeClassfile(classname, out);
  473. }
  474. /**
  475. * Reads class files from the source and returns an array of
  476. * <code>CtClass</code>
  477. * objects representing those class files.
  478. *
  479. * <p>If an element of <code>classnames</code> ends with "[]",
  480. * then this method
  481. * returns a <code>CtClass</code> object for that array type.
  482. *
  483. * @param classnames an array of fully-qualified class name.
  484. */
  485. public CtClass[] get(String[] classnames) throws NotFoundException {
  486. if (classnames == null)
  487. return new CtClass[0];
  488. int num = classnames.length;
  489. CtClass[] result = new CtClass[num];
  490. for (int i = 0; i < num; ++i)
  491. result[i] = get(classnames[i]);
  492. return result;
  493. }
  494. /**
  495. * Reads a class file and obtains a compile-time method.
  496. *
  497. * @param classname the class name
  498. * @param methodname the method name
  499. * @see CtClass#getDeclaredMethod(String)
  500. */
  501. public CtMethod getMethod(String classname, String methodname)
  502. throws NotFoundException
  503. {
  504. CtClass c = get(classname);
  505. return c.getDeclaredMethod(methodname);
  506. }
  507. /**
  508. * Creates a new class (or interface) from the given class file.
  509. * If there already exists a class with the same name, the new class
  510. * overwrites that previous class.
  511. *
  512. * <p>This method is used for creating a <code>CtClass</code> object
  513. * directly from a class file. The qualified class name is obtained
  514. * from the class file; you do not have to explicitly give the name.
  515. *
  516. * @param classfile class file.
  517. * @throws RuntimeException if there is a frozen class with the
  518. * the same name.
  519. * @see javassist.ByteArrayClassPath
  520. */
  521. public CtClass makeClass(InputStream classfile)
  522. throws IOException, RuntimeException {
  523. classfile = new BufferedInputStream(classfile);
  524. CtClass clazz = new CtClassType(classfile, this);
  525. clazz.checkModify();
  526. String classname = clazz.getName();
  527. checkNotFrozen(classname);
  528. cacheCtClass(classname, clazz, true);
  529. return clazz;
  530. }
  531. /**
  532. * Creates a new public class.
  533. * If there already exists a class with the same name, the new class
  534. * overwrites that previous class.
  535. *
  536. * @param classname a fully-qualified class name.
  537. * @throws RuntimeException if the existing class is frozen.
  538. */
  539. public CtClass makeClass(String classname) throws RuntimeException {
  540. return makeClass(classname, null);
  541. }
  542. /**
  543. * Creates a new public class.
  544. * If there already exists a class/interface with the same name,
  545. * the new class overwrites that previous class.
  546. *
  547. * @param classname a fully-qualified class name.
  548. * @param superclass the super class.
  549. * @throws RuntimeException if the existing class is frozen.
  550. */
  551. public synchronized CtClass makeClass(String classname, CtClass superclass)
  552. throws RuntimeException
  553. {
  554. checkNotFrozen(classname);
  555. CtClass clazz = new CtNewClass(classname, this, false, superclass);
  556. cacheCtClass(classname, clazz, true);
  557. return clazz;
  558. }
  559. /**
  560. * Creates a new public nested class.
  561. * This method is called by CtClassType.makeNestedClass().
  562. *
  563. * @param classname a fully-qualified class name.
  564. * @return the nested class.
  565. */
  566. synchronized CtClass makeNestedClass(String classname) {
  567. checkNotFrozen(classname);
  568. CtClass clazz = new CtNewNestedClass(classname, this, false, null);
  569. cacheCtClass(classname, clazz, true);
  570. return clazz;
  571. }
  572. /**
  573. * Creates a new public interface.
  574. * If there already exists a class/interface with the same name,
  575. * the new interface overwrites that previous one.
  576. *
  577. * @param name a fully-qualified interface name.
  578. * @throws RuntimeException if the existing interface is frozen.
  579. */
  580. public CtClass makeInterface(String name) throws RuntimeException {
  581. return makeInterface(name, null);
  582. }
  583. /**
  584. * Creates a new public interface.
  585. * If there already exists a class/interface with the same name,
  586. * the new interface overwrites that previous one.
  587. *
  588. * @param name a fully-qualified interface name.
  589. * @param superclass the super interface.
  590. * @throws RuntimeException if the existing interface is frozen.
  591. */
  592. public synchronized CtClass makeInterface(String name, CtClass superclass)
  593. throws RuntimeException
  594. {
  595. checkNotFrozen(name);
  596. CtClass clazz = new CtNewClass(name, this, true, superclass);
  597. cacheCtClass(name, clazz, true);
  598. return clazz;
  599. }
  600. /**
  601. * Appends the system search path to the end of the
  602. * search path. The system search path
  603. * usually includes the platform library, extension
  604. * libraries, and the search path specified by the
  605. * <code>-classpath</code> option or the <code>CLASSPATH</code>
  606. * environment variable.
  607. *
  608. * @return the appended class path.
  609. */
  610. public ClassPath appendSystemPath() {
  611. return source.appendSystemPath();
  612. }
  613. /**
  614. * Insert a <code>ClassPath</code> object at the head of the
  615. * search path.
  616. *
  617. * @return the inserted class path.
  618. * @see javassist.ClassPath
  619. * @see javassist.URLClassPath
  620. * @see javassist.ByteArrayClassPath
  621. */
  622. public ClassPath insertClassPath(ClassPath cp) {
  623. return source.insertClassPath(cp);
  624. }
  625. /**
  626. * Appends a <code>ClassPath</code> object to the end of the
  627. * search path.
  628. *
  629. * @return the appended class path.
  630. * @see javassist.ClassPath
  631. * @see javassist.URLClassPath
  632. * @see javassist.ByteArrayClassPath
  633. */
  634. public ClassPath appendClassPath(ClassPath cp) {
  635. return source.appendClassPath(cp);
  636. }
  637. /**
  638. * Inserts a directory or a jar (or zip) file at the head of the
  639. * search path.
  640. *
  641. * @param pathname the path name of the directory or jar file.
  642. * It must not end with a path separator ("/").
  643. * @return the inserted class path.
  644. * @throws NotFoundException if the jar file is not found.
  645. */
  646. public ClassPath insertClassPath(String pathname)
  647. throws NotFoundException
  648. {
  649. return source.insertClassPath(pathname);
  650. }
  651. /**
  652. * Appends a directory or a jar (or zip) file to the end of the
  653. * search path.
  654. *
  655. * @param pathname the path name of the directory or jar file.
  656. * It must not end with a path separator ("/").
  657. * @return the appended class path.
  658. * @throws NotFoundException if the jar file is not found.
  659. */
  660. public ClassPath appendClassPath(String pathname)
  661. throws NotFoundException
  662. {
  663. return source.appendClassPath(pathname);
  664. }
  665. /**
  666. * Detatches the <code>ClassPath</code> object from the search path.
  667. * The detached <code>ClassPath</code> object cannot be added
  668. * to the pathagain.
  669. */
  670. public void removeClassPath(ClassPath cp) {
  671. source.removeClassPath(cp);
  672. }
  673. /**
  674. * Appends directories and jar files for search.
  675. *
  676. * <p>The elements of the given path list must be separated by colons
  677. * in Unix or semi-colons in Windows.
  678. *
  679. * @param pathlist a (semi)colon-separated list of
  680. * the path names of directories and jar files.
  681. * The directory name must not end with a path
  682. * separator ("/").
  683. * @throws NotFoundException if a jar file is not found.
  684. */
  685. public void appendPathList(String pathlist) throws NotFoundException {
  686. char sep = File.pathSeparatorChar;
  687. int i = 0;
  688. for (;;) {
  689. int j = pathlist.indexOf(sep, i);
  690. if (j < 0) {
  691. appendClassPath(pathlist.substring(i));
  692. break;
  693. }
  694. else {
  695. appendClassPath(pathlist.substring(i, j));
  696. i = j + 1;
  697. }
  698. }
  699. }
  700. /**
  701. * Converts the given class to a <code>java.lang.Class</code> object.
  702. * Once this method is called, further modifications are not
  703. * allowed any more.
  704. * To load the class, this method uses the context class loader
  705. * of the current thread. It is obtained by calling
  706. * <code>getClassLoader()</code>.
  707. *
  708. * <p>This behavior can be changed by subclassing the pool and changing
  709. * the <code>getClassLoader()</code> method.
  710. * If the program is running on some application
  711. * server, the context class loader might be inappropriate to load the
  712. * class.
  713. *
  714. * <p>This method is provided for convenience. If you need more
  715. * complex functionality, you should write your own class loader.
  716. *
  717. * <p><b>Warining:</b> A Class object returned by this method may not
  718. * work with a security manager or a signed jar file because a
  719. * protection domain is not specified.
  720. *
  721. * @see #toClass(CtClass, java.lang.ClassLoader, ProtectionDomain)
  722. * @see #getClassLoader()
  723. */
  724. public Class toClass(CtClass clazz) throws CannotCompileException {
  725. return toClass(clazz, getClassLoader(), null);
  726. }
  727. /**
  728. * Get the classloader for <code>toClass()</code>, <code>getAnnotations()</code> in
  729. * <code>CtClass</code>, etc.
  730. *
  731. * <p>The default is the context class loader.
  732. *
  733. * @return the classloader for the pool
  734. * @see #toClass(CtClass)
  735. * @see CtClass#getAnnotations()
  736. */
  737. public ClassLoader getClassLoader() {
  738. return getContextClassLoader();
  739. }
  740. /**
  741. * Obtains a class loader that seems appropriate to look up a class
  742. * by name.
  743. */
  744. static ClassLoader getContextClassLoader() {
  745. return Thread.currentThread().getContextClassLoader();
  746. }
  747. /**
  748. * Converts the class to a <code>java.lang.Class</code> object.
  749. * Do not override this method any more at a subclass because
  750. * <code>toClass(CtClass)</code> never calls this method.
  751. *
  752. * <p><b>Warining:</b> A Class object returned by this method may not
  753. * work with a security manager or a signed jar file because a
  754. * protection domain is not specified.
  755. *
  756. * @deprecated Replaced by {@link #toClass(CtClass,ClassLoader,ProtectionDomain)}
  757. */
  758. public final Class toClass(CtClass ct, ClassLoader loader)
  759. throws CannotCompileException
  760. {
  761. return toClass(ct, loader, null);
  762. }
  763. /**
  764. * Converts the class to a <code>java.lang.Class</code> object.
  765. * Once this method is called, further modifications are not allowed
  766. * any more.
  767. *
  768. * <p>The class file represented by the given <code>CtClass</code> is
  769. * loaded by the given class loader to construct a
  770. * <code>java.lang.Class</code> object. Since a private method
  771. * on the class loader is invoked through the reflection API,
  772. * the caller must have permissions to do that.
  773. *
  774. * <p>An easy way to obtain <code>ProtectionDomain</code> object is
  775. * to call <code>getProtectionDomain()</code>
  776. * in <code>java.lang.Class</code>. It returns the domain that the
  777. * class belongs to.
  778. *
  779. * <p>This method is provided for convenience. If you need more
  780. * complex functionality, you should write your own class loader.
  781. *
  782. * @param loader the class loader used to load this class.
  783. * For example, the loader returned by
  784. * <code>getClassLoader()</code> can be used
  785. * for this parameter.
  786. * @param domain the protection domain for the class.
  787. * If it is null, the default domain created
  788. * by <code>java.lang.ClassLoader</code> is used.
  789. *
  790. * @see #getContextClassLoader()
  791. * @since 3.3
  792. */
  793. public Class toClass(CtClass ct, ClassLoader loader, ProtectionDomain domain)
  794. throws CannotCompileException
  795. {
  796. try {
  797. byte[] b = ct.toBytecode();
  798. java.lang.reflect.Method method;
  799. Object[] args;
  800. if (domain == null) {
  801. method = defineClass1;
  802. args = new Object[] { ct.getName(), b, new Integer(0),
  803. new Integer(b.length)};
  804. }
  805. else {
  806. method = defineClass2;
  807. args = new Object[] { ct.getName(), b, new Integer(0),
  808. new Integer(b.length), domain};
  809. }
  810. method.setAccessible(true);
  811. Class clazz = (Class)method.invoke(loader, args);
  812. method.setAccessible(false);
  813. return clazz;
  814. }
  815. catch (RuntimeException e) {
  816. throw e;
  817. }
  818. catch (java.lang.reflect.InvocationTargetException e) {
  819. throw new CannotCompileException(e.getTargetException());
  820. }
  821. catch (Exception e) {
  822. throw new CannotCompileException(e);
  823. }
  824. }
  825. }