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

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