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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270
  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.net.URL;
  23. import java.security.ProtectionDomain;
  24. import java.util.ArrayList;
  25. import java.util.Enumeration;
  26. import java.util.Hashtable;
  27. import java.util.Iterator;
  28. import javassist.bytecode.ClassFile;
  29. import javassist.bytecode.Descriptor;
  30. import javassist.util.proxy.DefinePackageHelper;
  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. @SuppressWarnings({"unchecked", "rawtypes"})
  66. public class ClassPool {
  67. /**
  68. * Determines the search order.
  69. *
  70. * <p>If this field is true, <code>get()</code> first searches the
  71. * class path associated to this <code>ClassPool</code> and then
  72. * the class path associated with the parent <code>ClassPool</code>.
  73. * Otherwise, the class path associated with the parent is searched
  74. * first.
  75. *
  76. * <p>The default value is false.
  77. */
  78. public boolean childFirstLookup = false;
  79. /**
  80. * Turning the automatic pruning on/off.
  81. *
  82. * <p>If this field is true, <code>CtClass</code> objects are
  83. * automatically pruned by default when <code>toBytecode()</code> etc.
  84. * are called. The automatic pruning can be turned on/off individually
  85. * for each <code>CtClass</code> object.
  86. *
  87. * <p>The initial value is false.
  88. *
  89. * @see CtClass#prune()
  90. * @see CtClass#stopPruning(boolean)
  91. * @see CtClass#detach()
  92. */
  93. public static boolean doPruning = false;
  94. private int compressCount;
  95. private static final int COMPRESS_THRESHOLD = 100;
  96. /* releaseUnmodifiedClassFile was introduced for avoiding a bug
  97. of JBoss AOP. So the value should be true except for JBoss AOP.
  98. */
  99. /**
  100. * If true, unmodified and not-recently-used class files are
  101. * periodically released for saving memory.
  102. *
  103. * <p>The initial value is true.
  104. */
  105. public static boolean releaseUnmodifiedClassFile = true;
  106. protected ClassPoolTail source;
  107. protected ClassPool parent;
  108. protected Hashtable classes; // should be synchronous
  109. /**
  110. * Table of registered cflow variables.
  111. */
  112. private Hashtable cflow = null; // should be synchronous.
  113. private static final int INIT_HASH_SIZE = 191;
  114. private ArrayList importedPackages;
  115. /**
  116. * Creates a root class pool. No parent class pool is specified.
  117. */
  118. public ClassPool() {
  119. this(null);
  120. }
  121. /**
  122. * Creates a root class pool. If <code>useDefaultPath</code> is
  123. * true, <code>appendSystemPath()</code> is called. Otherwise,
  124. * this constructor is equivalent to the constructor taking no
  125. * parameter.
  126. *
  127. * @param useDefaultPath true if the system search path is
  128. * appended.
  129. */
  130. public ClassPool(boolean useDefaultPath) {
  131. this(null);
  132. if (useDefaultPath)
  133. appendSystemPath();
  134. }
  135. /**
  136. * Creates a class pool.
  137. *
  138. * @param parent the parent of this class pool. If this is a root
  139. * class pool, this parameter must be <code>null</code>.
  140. * @see javassist.ClassPool#getDefault()
  141. */
  142. public ClassPool(ClassPool parent) {
  143. this.classes = new Hashtable(INIT_HASH_SIZE);
  144. this.source = new ClassPoolTail();
  145. this.parent = parent;
  146. if (parent == null) {
  147. CtClass[] pt = CtClass.primitiveTypes;
  148. for (int i = 0; i < pt.length; ++i)
  149. classes.put(pt[i].getName(), pt[i]);
  150. }
  151. this.cflow = null;
  152. this.compressCount = 0;
  153. clearImportedPackages();
  154. }
  155. /**
  156. * Returns the default class pool.
  157. * The returned object is always identical since this method is
  158. * a singleton factory.
  159. *
  160. * <p>The default class pool searches the system search path,
  161. * which usually includes the platform library, extension
  162. * libraries, and the search path specified by the
  163. * <code>-classpath</code> option or the <code>CLASSPATH</code>
  164. * environment variable.
  165. *
  166. * <p>When this method is called for the first time, the default
  167. * class pool is created with the following code snippet:
  168. *
  169. * <pre>ClassPool cp = new ClassPool();
  170. * cp.appendSystemPath();
  171. * </pre>
  172. *
  173. * <p>If the default class pool cannot find any class files,
  174. * try <code>ClassClassPath</code>, <code>ModuleClassPath</code>,
  175. * or <code>LoaderClassPath</code>.
  176. *
  177. * @see ClassClassPath
  178. * @see LoaderClassPath
  179. */
  180. public static synchronized ClassPool getDefault() {
  181. if (defaultPool == null) {
  182. defaultPool = new ClassPool(null);
  183. defaultPool.appendSystemPath();
  184. }
  185. return defaultPool;
  186. }
  187. private static ClassPool defaultPool = null;
  188. /**
  189. * Provide a hook so that subclasses can do their own
  190. * caching of classes.
  191. *
  192. * @see #cacheCtClass(String,CtClass,boolean)
  193. * @see #removeCached(String)
  194. */
  195. protected CtClass getCached(String classname) {
  196. return (CtClass)classes.get(classname);
  197. }
  198. /**
  199. * Provides a hook so that subclasses can do their own
  200. * caching of classes.
  201. *
  202. * @see #getCached(String)
  203. * @see #removeCached(String)
  204. */
  205. protected void cacheCtClass(String classname, CtClass c, boolean dynamic) {
  206. classes.put(classname, c);
  207. }
  208. /**
  209. * Provide a hook so that subclasses can do their own
  210. * caching of classes.
  211. *
  212. * @see #getCached(String)
  213. * @see #cacheCtClass(String,CtClass,boolean)
  214. */
  215. protected CtClass removeCached(String classname) {
  216. return (CtClass)classes.remove(classname);
  217. }
  218. /**
  219. * Returns the class search path.
  220. */
  221. public String toString() {
  222. return source.toString();
  223. }
  224. /**
  225. * This method is periodically invoked so that memory
  226. * footprint will be minimized.
  227. */
  228. void compress() {
  229. if (compressCount++ > COMPRESS_THRESHOLD) {
  230. compressCount = 0;
  231. Enumeration e = classes.elements();
  232. while (e.hasMoreElements())
  233. ((CtClass)e.nextElement()).compress();
  234. }
  235. }
  236. /**
  237. * Record a package name so that the Javassist compiler searches
  238. * the package to resolve a class name.
  239. * Don't record the <code>java.lang</code> package, which has
  240. * been implicitly recorded by default.
  241. *
  242. * <p>Since version 3.14, <code>packageName</code> can be a
  243. * fully-qualified class name.
  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<String> getImportedPackages() {
  274. return importedPackages.iterator();
  275. }
  276. /**
  277. * Records a class 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> quickly throw an exception
  281. * without searching the class path at all
  282. * if the given name is an invalid name recorded by this method.
  283. * Note that searching the class path takes relatively long time.
  284. *
  285. * <p>The current implementation of this method performs nothing.
  286. *
  287. * @param name an invalid class name (separeted by dots).
  288. * @deprecated
  289. */
  290. public void recordInvalidClassName(String name) {
  291. // source.recordInvalidClassName(name);
  292. }
  293. /**
  294. * Records the <code>$cflow</code> variable for the field specified
  295. * by <code>cname</code> and <code>fname</code>.
  296. *
  297. * @param name variable name
  298. * @param cname class name
  299. * @param fname field name
  300. */
  301. void recordCflow(String name, String cname, String fname) {
  302. if (cflow == null)
  303. cflow = new Hashtable();
  304. cflow.put(name, new Object[] { cname, fname });
  305. }
  306. /**
  307. * Undocumented method. Do not use; internal-use only.
  308. *
  309. * @param name the name of <code>$cflow</code> variable
  310. */
  311. public Object[] lookupCflow(String name) {
  312. if (cflow == null)
  313. cflow = new Hashtable();
  314. return (Object[])cflow.get(name);
  315. }
  316. /**
  317. * Reads a class file and constructs a <code>CtClass</code>
  318. * object with a new name.
  319. * This method is useful if you want to generate a new class as a copy
  320. * of another class (except the class name). For example,
  321. *
  322. * <pre>
  323. * getAndRename("Point", "Pair")
  324. * </pre>
  325. *
  326. * returns a <code>CtClass</code> object representing <code>Pair</code>
  327. * class. The definition of <code>Pair</code> is the same as that of
  328. * <code>Point</code> class except the class name since <code>Pair</code>
  329. * is defined by reading <code>Point.class</code>.
  330. *
  331. * @param orgName the original (fully-qualified) class name
  332. * @param newName the new class name
  333. */
  334. public CtClass getAndRename(String orgName, String newName)
  335. throws NotFoundException
  336. {
  337. CtClass clazz = get0(orgName, false);
  338. if (clazz == null)
  339. throw new NotFoundException(orgName);
  340. if (clazz instanceof CtClassType)
  341. ((CtClassType)clazz).setClassPool(this);
  342. clazz.setName(newName); // indirectly calls
  343. // classNameChanged() in this class
  344. return clazz;
  345. }
  346. /*
  347. * This method is invoked by CtClassType.setName(). It removes a
  348. * CtClass object from the hash table and inserts it with the new
  349. * name. Don't delegate to the parent.
  350. */
  351. synchronized void classNameChanged(String oldname, CtClass clazz) {
  352. CtClass c = (CtClass)getCached(oldname);
  353. if (c == clazz) // must check this equation.
  354. removeCached(oldname); // see getAndRename().
  355. String newName = clazz.getName();
  356. checkNotFrozen(newName);
  357. cacheCtClass(newName, clazz, false);
  358. }
  359. /**
  360. * Reads a class file from the source and returns a reference
  361. * to the <code>CtClass</code>
  362. * object representing that class file. If that class file has been
  363. * already read, this method returns a reference to the
  364. * <code>CtClass</code> created when that class file was read at the
  365. * first time.
  366. *
  367. * <p>If <code>classname</code> ends with "[]", then this method
  368. * returns a <code>CtClass</code> object for that array type.
  369. *
  370. * <p>To obtain an inner class, use "$" instead of "." for separating
  371. * the enclosing class name and the inner class name.
  372. *
  373. * @param classname a fully-qualified class name.
  374. */
  375. public CtClass get(String classname) throws NotFoundException {
  376. CtClass clazz;
  377. if (classname == null)
  378. clazz = null;
  379. else
  380. clazz = get0(classname, true);
  381. if (clazz == null)
  382. throw new NotFoundException(classname);
  383. else {
  384. clazz.incGetCounter();
  385. return clazz;
  386. }
  387. }
  388. /**
  389. * Reads a class file from the source and returns a reference
  390. * to the <code>CtClass</code>
  391. * object representing that class file.
  392. * This method is equivalent to <code>get</code> except
  393. * that it returns <code>null</code> when a class file is
  394. * not found and it never throws an exception.
  395. *
  396. * @param classname a fully-qualified class name.
  397. * @return a <code>CtClass</code> object or <code>null</code>.
  398. * @see #get(String)
  399. * @see #find(String)
  400. * @since 3.13
  401. */
  402. public CtClass getOrNull(String classname) {
  403. CtClass clazz = null;
  404. if (classname == null)
  405. clazz = null;
  406. else
  407. try {
  408. /* ClassPool.get0() never throws an exception
  409. but its subclass may implement get0 that
  410. may throw an exception.
  411. */
  412. clazz = get0(classname, true);
  413. }
  414. catch (NotFoundException e){}
  415. if (clazz != null)
  416. clazz.incGetCounter();
  417. return clazz;
  418. }
  419. /**
  420. * Returns a <code>CtClass</code> object with the given name.
  421. * This is almost equivalent to <code>get(String)</code> except
  422. * that classname can be an array-type "descriptor" (an encoded
  423. * type name) such as <code>[Ljava/lang/Object;</code>.
  424. *
  425. * <p>Using this method is not recommended; this method should be
  426. * used only to obtain the <code>CtClass</code> object
  427. * with a name returned from <code>getClassInfo</code> in
  428. * <code>javassist.bytecode.ClassPool</code>. <code>getClassInfo</code>
  429. * returns a fully-qualified class name but, if the class is an array
  430. * type, it returns a descriptor.
  431. *
  432. * @param classname a fully-qualified class name or a descriptor
  433. * representing an array type.
  434. * @see #get(String)
  435. * @see javassist.bytecode.ConstPool#getClassInfo(int)
  436. * @see javassist.bytecode.Descriptor#toCtClass(String, ClassPool)
  437. * @since 3.8.1
  438. */
  439. public CtClass getCtClass(String classname) throws NotFoundException {
  440. if (classname.charAt(0) == '[')
  441. return Descriptor.toCtClass(classname, this);
  442. else
  443. return get(classname);
  444. }
  445. /**
  446. * @param useCache false if the cached CtClass must be ignored.
  447. * @return null if the class could not be found.
  448. */
  449. protected synchronized CtClass get0(String classname, boolean useCache)
  450. throws NotFoundException
  451. {
  452. CtClass clazz = null;
  453. if (useCache) {
  454. clazz = getCached(classname);
  455. if (clazz != null)
  456. return clazz;
  457. }
  458. if (!childFirstLookup && parent != null) {
  459. clazz = parent.get0(classname, useCache);
  460. if (clazz != null)
  461. return clazz;
  462. }
  463. clazz = createCtClass(classname, useCache);
  464. if (clazz != null) {
  465. // clazz.getName() != classname if classname is "[L<name>;".
  466. if (useCache)
  467. cacheCtClass(clazz.getName(), clazz, false);
  468. return clazz;
  469. }
  470. if (childFirstLookup && parent != null)
  471. clazz = parent.get0(classname, useCache);
  472. return clazz;
  473. }
  474. /**
  475. * Creates a CtClass object representing the specified class.
  476. * It first examines whether or not the corresponding class
  477. * file exists. If yes, it creates a CtClass object.
  478. *
  479. * @return null if the class file could not be found.
  480. */
  481. protected CtClass createCtClass(String classname, boolean useCache) {
  482. // accept "[L<class name>;" as a class name.
  483. if (classname.charAt(0) == '[')
  484. classname = Descriptor.toClassName(classname);
  485. if (classname.endsWith("[]")) {
  486. String base = classname.substring(0, classname.indexOf('['));
  487. if ((!useCache || getCached(base) == null) && find(base) == null)
  488. return null;
  489. else
  490. return new CtArray(classname, this);
  491. }
  492. else
  493. if (find(classname) == null)
  494. return null;
  495. else
  496. return new CtClassType(classname, this);
  497. }
  498. /**
  499. * Searches the class path to obtain the URL of the class file
  500. * specified by classname. It is also used to determine whether
  501. * the class file exists.
  502. *
  503. * @param classname a fully-qualified class name.
  504. * @return null if the class file could not be found.
  505. * @see CtClass#getURL()
  506. */
  507. public URL find(String classname) {
  508. return source.find(classname);
  509. }
  510. /*
  511. * Is invoked by CtClassType.setName() and methods in this class.
  512. * This method throws an exception if the class is already frozen or
  513. * if this class pool cannot edit the class since it is in a parent
  514. * class pool.
  515. *
  516. * @see checkNotExists(String)
  517. */
  518. void checkNotFrozen(String classname) throws RuntimeException {
  519. CtClass clazz = getCached(classname);
  520. if (clazz == null) {
  521. if (!childFirstLookup && parent != null) {
  522. try {
  523. clazz = parent.get0(classname, true);
  524. }
  525. catch (NotFoundException e) {}
  526. if (clazz != null)
  527. throw new RuntimeException(classname
  528. + " is in a parent ClassPool. Use the parent.");
  529. }
  530. }
  531. else
  532. if (clazz.isFrozen())
  533. throw new RuntimeException(classname
  534. + ": frozen class (cannot edit)");
  535. }
  536. /*
  537. * This method returns null if this or its parent class pool does
  538. * not contain a CtClass object with the class name.
  539. *
  540. * @see checkNotFrozen(String)
  541. */
  542. CtClass checkNotExists(String classname) {
  543. CtClass clazz = getCached(classname);
  544. if (clazz == null)
  545. if (!childFirstLookup && parent != null) {
  546. try {
  547. clazz = parent.get0(classname, true);
  548. }
  549. catch (NotFoundException e) {}
  550. }
  551. return clazz;
  552. }
  553. /* for CtClassType.getClassFile2(). Don't delegate to the parent.
  554. */
  555. InputStream openClassfile(String classname) throws NotFoundException {
  556. return source.openClassfile(classname);
  557. }
  558. void writeClassfile(String classname, OutputStream out)
  559. throws NotFoundException, IOException, CannotCompileException
  560. {
  561. source.writeClassfile(classname, out);
  562. }
  563. /**
  564. * Reads class files from the source and returns an array of
  565. * <code>CtClass</code>
  566. * objects representing those class files.
  567. *
  568. * <p>If an element of <code>classnames</code> ends with "[]",
  569. * then this method
  570. * returns a <code>CtClass</code> object for that array type.
  571. *
  572. * @param classnames an array of fully-qualified class name.
  573. */
  574. public CtClass[] get(String[] classnames) throws NotFoundException {
  575. if (classnames == null)
  576. return new CtClass[0];
  577. int num = classnames.length;
  578. CtClass[] result = new CtClass[num];
  579. for (int i = 0; i < num; ++i)
  580. result[i] = get(classnames[i]);
  581. return result;
  582. }
  583. /**
  584. * Reads a class file and obtains a compile-time method.
  585. *
  586. * @param classname the class name
  587. * @param methodname the method name
  588. * @see CtClass#getDeclaredMethod(String)
  589. */
  590. public CtMethod getMethod(String classname, String methodname)
  591. throws NotFoundException
  592. {
  593. CtClass c = get(classname);
  594. return c.getDeclaredMethod(methodname);
  595. }
  596. /**
  597. * Creates a new class (or interface) from the given class file.
  598. * If there already exists a class with the same name, the new class
  599. * overwrites that previous class.
  600. *
  601. * <p>This method is used for creating a <code>CtClass</code> object
  602. * directly from a class file. The qualified class name is obtained
  603. * from the class file; you do not have to explicitly give the name.
  604. *
  605. * @param classfile class file.
  606. * @throws RuntimeException if there is a frozen class with the
  607. * the same name.
  608. * @see #makeClassIfNew(InputStream)
  609. * @see javassist.ByteArrayClassPath
  610. */
  611. public CtClass makeClass(InputStream classfile)
  612. throws IOException, RuntimeException
  613. {
  614. return makeClass(classfile, true);
  615. }
  616. /**
  617. * Creates a new class (or interface) from the given class file.
  618. * If there already exists a class with the same name, the new class
  619. * overwrites that previous class.
  620. *
  621. * <p>This method is used for creating a <code>CtClass</code> object
  622. * directly from a class file. The qualified class name is obtained
  623. * from the class file; you do not have to explicitly give the name.
  624. *
  625. * @param classfile class file.
  626. * @param ifNotFrozen throws a RuntimeException if this parameter is true
  627. * and there is a frozen class with the same name.
  628. * @see javassist.ByteArrayClassPath
  629. */
  630. public CtClass makeClass(InputStream classfile, boolean ifNotFrozen)
  631. throws IOException, RuntimeException
  632. {
  633. compress();
  634. classfile = new BufferedInputStream(classfile);
  635. CtClass clazz = new CtClassType(classfile, this);
  636. clazz.checkModify();
  637. String classname = clazz.getName();
  638. if (ifNotFrozen)
  639. checkNotFrozen(classname);
  640. cacheCtClass(classname, clazz, true);
  641. return clazz;
  642. }
  643. /**
  644. * Creates a new class (or interface) from the given class file.
  645. * If there already exists a class with the same name, the new class
  646. * overwrites that previous class.
  647. *
  648. * <p>This method is used for creating a <code>CtClass</code> object
  649. * directly from a class file. The qualified class name is obtained
  650. * from the class file; you do not have to explicitly give the name.
  651. *
  652. * @param classfile class file.
  653. * @throws RuntimeException if there is a frozen class with the
  654. * the same name.
  655. * @since 3.20
  656. */
  657. public CtClass makeClass(ClassFile classfile)
  658. throws RuntimeException
  659. {
  660. return makeClass(classfile, true);
  661. }
  662. /**
  663. * Creates a new class (or interface) from the given class file.
  664. * If there already exists a class with the same name, the new class
  665. * overwrites that previous class.
  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 class file.
  672. * @param ifNotFrozen throws a RuntimeException if this parameter is true
  673. * and there is a frozen class with the same name.
  674. * @since 3.20
  675. */
  676. public CtClass makeClass(ClassFile classfile, boolean ifNotFrozen)
  677. throws RuntimeException
  678. {
  679. compress();
  680. CtClass clazz = new CtClassType(classfile, this);
  681. clazz.checkModify();
  682. String classname = clazz.getName();
  683. if (ifNotFrozen)
  684. checkNotFrozen(classname);
  685. cacheCtClass(classname, clazz, true);
  686. return clazz;
  687. }
  688. /**
  689. * Creates a new class (or interface) from the given class file.
  690. * If there already exists a class with the same name, this method
  691. * returns the existing class; a new class is never created from
  692. * the given class file.
  693. *
  694. * <p>This method is used for creating a <code>CtClass</code> object
  695. * directly from a class file. The qualified class name is obtained
  696. * from the class file; you do not have to explicitly give the name.
  697. *
  698. * @param classfile the class file.
  699. * @see #makeClass(InputStream)
  700. * @see javassist.ByteArrayClassPath
  701. * @since 3.9
  702. */
  703. public CtClass makeClassIfNew(InputStream classfile)
  704. throws IOException, RuntimeException
  705. {
  706. compress();
  707. classfile = new BufferedInputStream(classfile);
  708. CtClass clazz = new CtClassType(classfile, this);
  709. clazz.checkModify();
  710. String classname = clazz.getName();
  711. CtClass found = checkNotExists(classname);
  712. if (found != null)
  713. return found;
  714. else {
  715. cacheCtClass(classname, clazz, true);
  716. return clazz;
  717. }
  718. }
  719. /**
  720. * Creates a new public class.
  721. * If there already exists a class with the same name, the new class
  722. * overwrites that previous class.
  723. *
  724. * <p>If no constructor is explicitly added to the created new
  725. * class, Javassist generates constructors and adds it when
  726. * the class file is generated. It generates a new constructor
  727. * for each constructor of the super class. The new constructor
  728. * takes the same set of parameters and invokes the
  729. * corresponding constructor of the super class. All the received
  730. * parameters are passed to it.
  731. *
  732. * @param classname a fully-qualified class name.
  733. * @throws RuntimeException if the existing class is frozen.
  734. */
  735. public CtClass makeClass(String classname) throws RuntimeException {
  736. return makeClass(classname, null);
  737. }
  738. /**
  739. * Creates a new public class.
  740. * If there already exists a class/interface with the same name,
  741. * the new class overwrites that previous class.
  742. *
  743. * <p>If no constructor is explicitly added to the created new
  744. * class, Javassist generates constructors and adds it when
  745. * the class file is generated. It generates a new constructor
  746. * for each constructor of the super class. The new constructor
  747. * takes the same set of parameters and invokes the
  748. * corresponding constructor of the super class. All the received
  749. * parameters are passed to it.
  750. *
  751. * @param classname a fully-qualified class name.
  752. * @param superclass the super class.
  753. * @throws RuntimeException if the existing class is frozen.
  754. */
  755. public synchronized CtClass makeClass(String classname, CtClass superclass)
  756. throws RuntimeException
  757. {
  758. checkNotFrozen(classname);
  759. CtClass clazz = new CtNewClass(classname, this, false, superclass);
  760. cacheCtClass(classname, clazz, true);
  761. return clazz;
  762. }
  763. /**
  764. * Creates a new public nested class.
  765. * This method is called by {@link CtClassType#makeNestedClass()}.
  766. *
  767. * @param classname a fully-qualified class name.
  768. * @return the nested class.
  769. */
  770. synchronized CtClass makeNestedClass(String classname) {
  771. checkNotFrozen(classname);
  772. CtClass clazz = new CtNewClass(classname, this, false, null);
  773. cacheCtClass(classname, clazz, true);
  774. return clazz;
  775. }
  776. /**
  777. * Creates a new public interface.
  778. * If there already exists a class/interface with the same name,
  779. * the new interface overwrites that previous one.
  780. *
  781. * @param name a fully-qualified interface name.
  782. * @throws RuntimeException if the existing interface is frozen.
  783. */
  784. public CtClass makeInterface(String name) throws RuntimeException {
  785. return makeInterface(name, null);
  786. }
  787. /**
  788. * Creates a new public interface.
  789. * If there already exists a class/interface with the same name,
  790. * the new interface overwrites that previous one.
  791. *
  792. * @param name a fully-qualified interface name.
  793. * @param superclass the super interface.
  794. * @throws RuntimeException if the existing interface is frozen.
  795. */
  796. public synchronized CtClass makeInterface(String name, CtClass superclass)
  797. throws RuntimeException
  798. {
  799. checkNotFrozen(name);
  800. CtClass clazz = new CtNewClass(name, this, true, superclass);
  801. cacheCtClass(name, clazz, true);
  802. return clazz;
  803. }
  804. /**
  805. * Creates a new annotation.
  806. * If there already exists a class/interface with the same name,
  807. * the new interface overwrites that previous one.
  808. *
  809. * @param name a fully-qualified interface name.
  810. * Or null if the annotation has no super interface.
  811. * @throws RuntimeException if the existing interface is frozen.
  812. * @since 3.19
  813. */
  814. public CtClass makeAnnotation(String name) throws RuntimeException {
  815. try {
  816. CtClass cc = makeInterface(name, get("java.lang.annotation.Annotation"));
  817. cc.setModifiers(cc.getModifiers() | Modifier.ANNOTATION);
  818. return cc;
  819. }
  820. catch (NotFoundException e) {
  821. // should never happen.
  822. throw new RuntimeException(e.getMessage(), e);
  823. }
  824. }
  825. /**
  826. * Appends the system search path to the end of the
  827. * search path. The system search path
  828. * usually includes the platform library, extension
  829. * libraries, and the search path specified by the
  830. * <code>-classpath</code> option or the <code>CLASSPATH</code>
  831. * environment variable.
  832. *
  833. * @return the appended class path.
  834. */
  835. public ClassPath appendSystemPath() {
  836. return source.appendSystemPath();
  837. }
  838. /**
  839. * Insert a <code>ClassPath</code> object at the head of the
  840. * search path.
  841. *
  842. * @return the inserted class path.
  843. * @see javassist.ClassPath
  844. * @see javassist.URLClassPath
  845. * @see javassist.ByteArrayClassPath
  846. */
  847. public ClassPath insertClassPath(ClassPath cp) {
  848. return source.insertClassPath(cp);
  849. }
  850. /**
  851. * Appends a <code>ClassPath</code> object to the end of the
  852. * search path.
  853. *
  854. * @return the appended class path.
  855. * @see javassist.ClassPath
  856. * @see javassist.URLClassPath
  857. * @see javassist.ByteArrayClassPath
  858. */
  859. public ClassPath appendClassPath(ClassPath cp) {
  860. return source.appendClassPath(cp);
  861. }
  862. /**
  863. * Inserts a directory or a jar (or zip) file at the head of the
  864. * search path.
  865. *
  866. * @param pathname the path name of the directory or jar file.
  867. * It must not end with a path separator ("/").
  868. * If the path name ends with "/*", then all the
  869. * jar files matching the path name are inserted.
  870. *
  871. * @return the inserted class path.
  872. * @throws NotFoundException if the jar file is not found.
  873. */
  874. public ClassPath insertClassPath(String pathname)
  875. throws NotFoundException
  876. {
  877. return source.insertClassPath(pathname);
  878. }
  879. /**
  880. * Appends a directory or a jar (or zip) file to the end of the
  881. * search path.
  882. *
  883. * @param pathname the path name of the directory or jar file.
  884. * It must not end with a path separator ("/").
  885. * If the path name ends with "/*", then all the
  886. * jar files matching the path name are appended.
  887. *
  888. * @return the appended class path.
  889. * @throws NotFoundException if the jar file is not found.
  890. */
  891. public ClassPath appendClassPath(String pathname)
  892. throws NotFoundException
  893. {
  894. return source.appendClassPath(pathname);
  895. }
  896. /**
  897. * Detatches the <code>ClassPath</code> object from the search path.
  898. * The detached <code>ClassPath</code> object cannot be added
  899. * to the path again.
  900. */
  901. public void removeClassPath(ClassPath cp) {
  902. source.removeClassPath(cp);
  903. }
  904. /**
  905. * Appends directories and jar files for search.
  906. *
  907. * <p>The elements of the given path list must be separated by colons
  908. * in Unix or semi-colons in Windows.
  909. *
  910. * @param pathlist a (semi)colon-separated list of
  911. * the path names of directories and jar files.
  912. * The directory name must not end with a path
  913. * separator ("/").
  914. * @throws NotFoundException if a jar file is not found.
  915. */
  916. public void appendPathList(String pathlist) throws NotFoundException {
  917. char sep = File.pathSeparatorChar;
  918. int i = 0;
  919. for (;;) {
  920. int j = pathlist.indexOf(sep, i);
  921. if (j < 0) {
  922. appendClassPath(pathlist.substring(i));
  923. break;
  924. }
  925. else {
  926. appendClassPath(pathlist.substring(i, j));
  927. i = j + 1;
  928. }
  929. }
  930. }
  931. /**
  932. * Converts the given class to a <code>java.lang.Class</code> object.
  933. * Once this method is called, further modifications are not
  934. * allowed any more.
  935. * To load the class, this method uses the context class loader
  936. * of the current thread. It is obtained by calling
  937. * <code>getClassLoader()</code>.
  938. *
  939. * <p>This behavior can be changed by subclassing the pool and changing
  940. * the <code>getClassLoader()</code> method.
  941. * If the program is running on some application
  942. * server, the context class loader might be inappropriate to load the
  943. * class.</p>
  944. *
  945. * <p>This method is provided for convenience. If you need more
  946. * complex functionality, you should write your own class loader.
  947. *
  948. * <p><b>Warining:</b>
  949. * This method should not be used in Java 11 or later.
  950. * Use {@link #toClass(CtClass,Class)}.
  951. * </p>
  952. *
  953. * <p><b>Warining:</b>
  954. * A Class object returned by this method may not
  955. * work with a security manager or a signed jar file because a
  956. * protection domain is not specified.</p>
  957. *
  958. * @see #toCalss(CtClass,Class)
  959. * @see #toClass(CtClass,Class,java.lang.ClassLoader,ProtectionDomain)
  960. * @see #getClassLoader()
  961. */
  962. public Class toClass(CtClass clazz) throws CannotCompileException {
  963. // Some subclasses of ClassPool may override toClass(CtClass,ClassLoader).
  964. // So we should call that method instead of toClass(.., ProtectionDomain).
  965. return toClass(clazz, getClassLoader());
  966. }
  967. /**
  968. * Get the classloader for <code>toClass()</code>, <code>getAnnotations()</code> in
  969. * <code>CtClass</code>, etc.
  970. *
  971. * <p>The default is the context class loader.
  972. *
  973. * @return the classloader for the pool
  974. * @see #toClass(CtClass)
  975. * @see CtClass#getAnnotations()
  976. */
  977. public ClassLoader getClassLoader() {
  978. return getContextClassLoader();
  979. }
  980. /**
  981. * Obtains a class loader that seems appropriate to look up a class
  982. * by name.
  983. */
  984. static ClassLoader getContextClassLoader() {
  985. return Thread.currentThread().getContextClassLoader();
  986. }
  987. /**
  988. * Converts the class to a <code>java.lang.Class</code> object.
  989. * Do not override this method any more at a subclass because
  990. * {@link #toClass(CtClass)} will never calls this method.
  991. *
  992. * <p><b>Warining:</b> A Class object returned by this method may not
  993. * work with a security manager or a signed jar file because a
  994. * protection domain is not specified.
  995. *
  996. * @deprecated Replaced by {@link #toClass(CtClass,Class,ClassLoader,ProtectionDomain)}.
  997. * A subclass of <code>ClassPool</code> that has been
  998. * overriding this method should be modified. It should override
  999. * {@link #toClass(CtClass,Class,ClassLoader,ProtectionDomain)}.
  1000. */
  1001. public Class toClass(CtClass ct, ClassLoader loader)
  1002. throws CannotCompileException
  1003. {
  1004. return toClass(ct, null, loader, null);
  1005. }
  1006. /**
  1007. * Converts the class to a <code>java.lang.Class</code> object.
  1008. * Once this method is called, further modifications are not allowed
  1009. * any more.
  1010. *
  1011. * <p>The class file represented by the given <code>CtClass</code> is
  1012. * loaded by the given class loader to construct a
  1013. * <code>java.lang.Class</code> object. Since a private method
  1014. * on the class loader is invoked through the reflection API,
  1015. * the caller must have permissions to do that.</p>
  1016. *
  1017. * <p>An easy way to obtain <code>ProtectionDomain</code> object is
  1018. * to call <code>getProtectionDomain()</code>
  1019. * in <code>java.lang.Class</code>. It returns the domain that the
  1020. * class belongs to.
  1021. *
  1022. * <p>This method is provided for convenience. If you need more
  1023. * complex functionality, you should write your own class loader.</p>
  1024. *
  1025. * @param ct the class converted into {@code java.lang.Class}.
  1026. * @param loader the class loader used to load this class.
  1027. * For example, the loader returned by
  1028. * <code>getClassLoader()</code> can be used
  1029. * for this parameter.
  1030. * @param domain the protection domain for the class.
  1031. * If it is null, the default domain created
  1032. * by <code>java.lang.ClassLoader</code> is used.
  1033. *
  1034. * @see #getClassLoader()
  1035. * @since 3.3
  1036. * @deprecated Replaced by {@link #toClass(CtClass,Class,ClassLoader,ProtectionDomain)}.
  1037. */
  1038. public Class toClass(CtClass ct, ClassLoader loader, ProtectionDomain domain)
  1039. throws CannotCompileException
  1040. {
  1041. return toClass(ct, null, loader, domain);
  1042. }
  1043. /**
  1044. * Converts the class to a <code>java.lang.Class</code> object.
  1045. * Once this method is called, further modifications are not allowed
  1046. * any more.
  1047. *
  1048. * <p>This method is available in Java 9 or later.
  1049. * It loads the class
  1050. * by using {@code java.lang.invoke.MethodHandles} with {@code neighbor}.
  1051. * </p>
  1052. *
  1053. * @param ct the class converted into {@code java.lang.Class}.
  1054. * @param neighbor a class belonging to the same package that
  1055. * the converted class belongs to.
  1056. * @since 3.24
  1057. */
  1058. public Class<?> toClass(CtClass ct, Class<?> neighbor)
  1059. throws CannotCompileException
  1060. {
  1061. try {
  1062. return javassist.util.proxy.DefineClassHelper.toClass(neighbor,
  1063. ct.toBytecode());
  1064. }
  1065. catch (IOException e) {
  1066. throw new CannotCompileException(e);
  1067. }
  1068. }
  1069. /**
  1070. * Converts the class to a <code>java.lang.Class</code> object.
  1071. * Once this method is called, further modifications are not allowed
  1072. * any more.
  1073. *
  1074. * <p>This method is available in Java 9 or later.
  1075. * It loads the class
  1076. * by using the given {@code java.lang.invoke.MethodHandles.Lookup}.
  1077. * </p>
  1078. *
  1079. * @param ct the class converted into {@code java.lang.Class}.
  1080. * @since 3.24
  1081. */
  1082. public Class<?> toClass(CtClass ct,
  1083. java.lang.invoke.MethodHandles.Lookup lookup)
  1084. throws CannotCompileException
  1085. {
  1086. try {
  1087. return javassist.util.proxy.DefineClassHelper.toClass(lookup,
  1088. ct.toBytecode());
  1089. }
  1090. catch (IOException e) {
  1091. throw new CannotCompileException(e);
  1092. }
  1093. }
  1094. /**
  1095. * Converts the class to a <code>java.lang.Class</code> object.
  1096. * Once this method is called, further modifications are not allowed
  1097. * any more.
  1098. *
  1099. * <p>When the JVM is Java 11 or later, this method loads the class
  1100. * by using {@code java.lang.invoke.MethodHandles} with {@code neighbor}.
  1101. * The other arguments {@code loader} and {@code domain} are not used;
  1102. * so they can be null.
  1103. * </p>
  1104. *
  1105. * <p>Otherwise, or when {@code neighbor} is null,
  1106. * the class file represented by the given <code>CtClass</code> is
  1107. * loaded by the given class loader to construct a
  1108. * <code>java.lang.Class</code> object. Since a private method
  1109. * on the class loader is invoked through the reflection API,
  1110. * the caller must have permissions to do that.
  1111. *
  1112. * <p>An easy way to obtain <code>ProtectionDomain</code> object is
  1113. * to call <code>getProtectionDomain()</code>
  1114. * in <code>java.lang.Class</code>. It returns the domain that the
  1115. * class belongs to.
  1116. *
  1117. * <p>If your program is for only Java 9 or later, don't use this method.
  1118. * Use {@link #toClass(CtClass,Class)} or
  1119. * {@link #toClass(CtClass)CtClass,java.lang.invoke.MethodHandles.Lookup)}.
  1120. * </p>
  1121. *
  1122. * @param ct the class converted into {@code java.lang.Class}.
  1123. * @param neighbor a class belonging to the same package that
  1124. * the converted class belongs to.
  1125. * It can be null.
  1126. * @param loader the class loader used to load this class.
  1127. * For example, the loader returned by
  1128. * <code>getClassLoader()</code> can be used
  1129. * for this parameter.
  1130. * @param domain the protection domain for the class.
  1131. * If it is null, the default domain created
  1132. * by <code>java.lang.ClassLoader</code> is used.
  1133. *
  1134. * @see #getClassLoader()
  1135. * @since 3.24
  1136. */
  1137. public Class toClass(CtClass ct, Class<?> neighbor, ClassLoader loader,
  1138. ProtectionDomain domain)
  1139. throws CannotCompileException
  1140. {
  1141. try {
  1142. return javassist.util.proxy.DefineClassHelper.toClass(ct.getName(),
  1143. neighbor, loader, domain, ct.toBytecode());
  1144. }
  1145. catch (IOException e) {
  1146. throw new CannotCompileException(e);
  1147. }
  1148. }
  1149. /**
  1150. * Defines a new package. If the package is already defined, this method
  1151. * performs nothing.
  1152. *
  1153. * <p>You do not necessarily need to
  1154. * call this method. If this method is called, then
  1155. * <code>getPackage()</code> on the <code>Class</code> object returned
  1156. * by <code>toClass()</code> will return a non-null object.</p>
  1157. *
  1158. * <p>The jigsaw module introduced by Java 9 has broken this method.
  1159. * In Java 9 or later, the VM argument
  1160. * <code>--add-opens java.base/java.lang=ALL-UNNAMED</code>
  1161. * has to be given to the JVM so that this method can run.
  1162. * </p>
  1163. *
  1164. * @param loader the class loader passed to <code>toClass()</code> or
  1165. * the default one obtained by <code>getClassLoader()</code>.
  1166. * @param name the package name.
  1167. * @see #getClassLoader()
  1168. * @see #toClass(CtClass)
  1169. * @see CtClass#toClass()
  1170. * @since 3.16
  1171. * @deprecated
  1172. */
  1173. public void makePackage(ClassLoader loader, String name)
  1174. throws CannotCompileException
  1175. {
  1176. DefinePackageHelper.definePackage(name, loader);
  1177. }
  1178. }