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

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