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

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