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

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