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

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