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

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