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.

CtClass.java 50KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555
  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.BufferedOutputStream;
  18. import java.io.ByteArrayOutputStream;
  19. import java.io.DataOutputStream;
  20. import java.io.File;
  21. import java.io.FileOutputStream;
  22. import java.io.IOException;
  23. import java.io.OutputStream;
  24. import java.net.URL;
  25. import java.security.ProtectionDomain;
  26. import java.util.Collection;
  27. import javassist.bytecode.ClassFile;
  28. import javassist.bytecode.Descriptor;
  29. import javassist.bytecode.Opcode;
  30. import javassist.bytecode.SignatureAttribute;
  31. import javassist.expr.ExprEditor;
  32. /* Note:
  33. *
  34. * This class is an abstract class and several methods just return null
  35. * or throw an exception. Those methods are overridden in subclasses
  36. * of this class. Read the source code of CtClassType if you are
  37. * interested in the implementation of Javassist.
  38. *
  39. * Subclasses of CtClass are CtClassType, CtPrimitiveType, and CtArray.
  40. */
  41. /**
  42. * An instance of <code>CtClass</code> represents a class.
  43. * It is obtained from <code>ClassPool</code>.
  44. *
  45. * @see ClassPool#get(String)
  46. */
  47. public abstract class CtClass {
  48. protected String qualifiedName;
  49. /**
  50. * If the value of this field is not null, then all class
  51. * files modified by Javassist are saved under the directory
  52. * specified by this variable. For example, if the value is
  53. * <code>"./debug"</code>, then all class files are saved
  54. * there. The directory name must not end with a directory
  55. * separator such as <code>/</code>.
  56. *
  57. * <p>The default value is null.
  58. *
  59. * @see #debugWriteFile(String)
  60. * @since 3.16
  61. */
  62. public static String debugDump = null;
  63. /**
  64. * The version number of this release.
  65. */
  66. public static final String version = "3.17.1-GA";
  67. /**
  68. * Prints the version number and the copyright notice.
  69. *
  70. * <p>The following command invokes this method:
  71. *
  72. * <ul><pre>java -jar javassist.jar</pre></ul>
  73. */
  74. public static void main(String[] args) {
  75. System.out.println("Javassist version " + CtClass.version);
  76. System.out.println("Copyright (C) 1999-2012 Shigeru Chiba."
  77. + " All Rights Reserved.");
  78. }
  79. static final String javaLangObject = "java.lang.Object";
  80. /**
  81. * The <code>CtClass</code> object representing
  82. * the <code>boolean</code> type.
  83. */
  84. public static CtClass booleanType;
  85. /**
  86. * The <code>CtClass</code> object representing
  87. * the <code>char</code> type.
  88. */
  89. public static CtClass charType;
  90. /**
  91. * The <code>CtClass</code> object representing
  92. * the <code>byte</code> type.
  93. */
  94. public static CtClass byteType;
  95. /**
  96. * The <code>CtClass</code> object representing
  97. * the <code>short</code> type.
  98. */
  99. public static CtClass shortType;
  100. /**
  101. * The <code>CtClass</code> object representing
  102. * the <code>int</code> type.
  103. */
  104. public static CtClass intType;
  105. /**
  106. * The <code>CtClass</code> object representing
  107. * the <code>long</code> type.
  108. */
  109. public static CtClass longType;
  110. /**
  111. * The <code>CtClass</code> object representing
  112. * the <code>float</code> type.
  113. */
  114. public static CtClass floatType;
  115. /**
  116. * The <code>CtClass</code> object representing
  117. * the <code>double</code> type.
  118. */
  119. public static CtClass doubleType;
  120. /**
  121. * The <code>CtClass</code> object representing
  122. * the <code>void</code> type.
  123. */
  124. public static CtClass voidType;
  125. static CtClass[] primitiveTypes;
  126. static {
  127. primitiveTypes = new CtClass[9];
  128. booleanType =
  129. new CtPrimitiveType("boolean", 'Z', "java.lang.Boolean",
  130. "booleanValue", "()Z", Opcode.IRETURN,
  131. Opcode.T_BOOLEAN, 1);
  132. primitiveTypes[0] = booleanType;
  133. charType = new CtPrimitiveType("char", 'C', "java.lang.Character",
  134. "charValue", "()C", Opcode.IRETURN,
  135. Opcode.T_CHAR, 1);
  136. primitiveTypes[1] = charType;
  137. byteType = new CtPrimitiveType("byte", 'B', "java.lang.Byte",
  138. "byteValue", "()B", Opcode.IRETURN,
  139. Opcode.T_BYTE, 1);
  140. primitiveTypes[2] = byteType;
  141. shortType = new CtPrimitiveType("short", 'S', "java.lang.Short",
  142. "shortValue", "()S", Opcode.IRETURN,
  143. Opcode.T_SHORT, 1);
  144. primitiveTypes[3] = shortType;
  145. intType = new CtPrimitiveType("int", 'I', "java.lang.Integer",
  146. "intValue", "()I", Opcode.IRETURN,
  147. Opcode.T_INT, 1);
  148. primitiveTypes[4] = intType;
  149. longType = new CtPrimitiveType("long", 'J', "java.lang.Long",
  150. "longValue", "()J", Opcode.LRETURN,
  151. Opcode.T_LONG, 2);
  152. primitiveTypes[5] = longType;
  153. floatType = new CtPrimitiveType("float", 'F', "java.lang.Float",
  154. "floatValue", "()F", Opcode.FRETURN,
  155. Opcode.T_FLOAT, 1);
  156. primitiveTypes[6] = floatType;
  157. doubleType = new CtPrimitiveType("double", 'D', "java.lang.Double",
  158. "doubleValue", "()D", Opcode.DRETURN,
  159. Opcode.T_DOUBLE, 2);
  160. primitiveTypes[7] = doubleType;
  161. voidType = new CtPrimitiveType("void", 'V', "java.lang.Void",
  162. null, null, Opcode.RETURN, 0, 0);
  163. primitiveTypes[8] = voidType;
  164. }
  165. protected CtClass(String name) {
  166. qualifiedName = name;
  167. }
  168. /**
  169. * Converts the object to a string.
  170. */
  171. public String toString() {
  172. StringBuffer buf = new StringBuffer(getClass().getName());
  173. buf.append("@");
  174. buf.append(Integer.toHexString(hashCode()));
  175. buf.append("[");
  176. extendToString(buf);
  177. buf.append("]");
  178. return buf.toString();
  179. }
  180. /**
  181. * Implemented in subclasses to add to the {@link #toString()} result.
  182. * Subclasses should put a space before each token added to the buffer.
  183. */
  184. protected void extendToString(StringBuffer buffer) {
  185. buffer.append(getName());
  186. }
  187. /**
  188. * Returns a <code>ClassPool</code> for this class.
  189. */
  190. public ClassPool getClassPool() { return null; }
  191. /**
  192. * Returns a class file for this class.
  193. *
  194. * <p>This method is not available if <code>isFrozen()</code>
  195. * is true.
  196. */
  197. public ClassFile getClassFile() {
  198. checkModify();
  199. return getClassFile2();
  200. }
  201. /**
  202. * Returns a class file for this class (read only).
  203. * Normal applications do not need calling this method. Use
  204. * <code>getClassFile()</code>.
  205. *
  206. * <p>The <code>ClassFile</code> object obtained by this method
  207. * is read only. Changes to this object might not be reflected
  208. * on a class file generated by <code>toBytecode()</code>,
  209. * <code>toClass()</code>, etc.
  210. *
  211. * <p>This method is available even if <code>isFrozen()</code>
  212. * is true. However, if the class is frozen, it might be also
  213. * pruned.
  214. *
  215. * @see CtClass#getClassFile()
  216. * @see CtClass#isFrozen()
  217. * @see CtClass#prune()
  218. */
  219. public ClassFile getClassFile2() { return null; }
  220. /**
  221. * Undocumented method. Do not use; internal-use only.
  222. */
  223. public javassist.compiler.AccessorMaker getAccessorMaker() {
  224. return null;
  225. }
  226. /**
  227. * Returns the uniform resource locator (URL) of the class file.
  228. */
  229. public URL getURL() throws NotFoundException {
  230. throw new NotFoundException(getName());
  231. }
  232. /**
  233. * Returns true if the definition of the class has been modified.
  234. */
  235. public boolean isModified() { return false; }
  236. /**
  237. * Returns true if the class has been loaded or written out
  238. * and thus it cannot be modified any more.
  239. *
  240. * @see #defrost()
  241. * @see #detach()
  242. */
  243. public boolean isFrozen() { return true; }
  244. /**
  245. * Makes the class frozen.
  246. *
  247. * @see #isFrozen()
  248. * @see #defrost()
  249. * @since 3.6
  250. */
  251. public void freeze() {}
  252. /* Note: this method is overridden by CtClassType
  253. */
  254. void checkModify() throws RuntimeException {
  255. if (isFrozen())
  256. throw new RuntimeException(getName() + " class is frozen");
  257. // isModified() must return true after this method is invoked.
  258. }
  259. /**
  260. * Defrosts the class so that the class can be modified again.
  261. *
  262. * <p>To avoid changes that will be never reflected,
  263. * the class is frozen to be unmodifiable if it is loaded or
  264. * written out. This method should be called only in a case
  265. * that the class will be reloaded or written out later again.
  266. *
  267. * <p>If <code>defrost()</code> will be called later, pruning
  268. * must be disallowed in advance.
  269. *
  270. * @see #isFrozen()
  271. * @see #stopPruning(boolean)
  272. * @see #detach()
  273. */
  274. public void defrost() {
  275. throw new RuntimeException("cannot defrost " + getName());
  276. }
  277. /**
  278. * Returns <code>true</code> if this object represents a primitive
  279. * Java type: boolean, byte, char, short, int, long, float, double,
  280. * or void.
  281. */
  282. public boolean isPrimitive() { return false; }
  283. /**
  284. * Returns <code>true</code> if this object represents an array type.
  285. */
  286. public boolean isArray() {
  287. return false;
  288. }
  289. /**
  290. * If this object represents an array, this method returns the component
  291. * type of the array. Otherwise, it returns <code>null</code>.
  292. */
  293. public CtClass getComponentType() throws NotFoundException {
  294. return null;
  295. }
  296. /**
  297. * Returns <code>true</code> if this class extends or implements
  298. * <code>clazz</code>. It also returns <code>true</code> if
  299. * this class is the same as <code>clazz</code>.
  300. */
  301. public boolean subtypeOf(CtClass clazz) throws NotFoundException {
  302. return this == clazz || getName().equals(clazz.getName());
  303. }
  304. /**
  305. * Obtains the fully-qualified name of the class.
  306. */
  307. public String getName() { return qualifiedName; }
  308. /**
  309. * Obtains the not-qualified class name.
  310. */
  311. public final String getSimpleName() {
  312. String qname = qualifiedName;
  313. int index = qname.lastIndexOf('.');
  314. if (index < 0)
  315. return qname;
  316. else
  317. return qname.substring(index + 1);
  318. }
  319. /**
  320. * Obtains the package name. It may be <code>null</code>.
  321. */
  322. public final String getPackageName() {
  323. String qname = qualifiedName;
  324. int index = qname.lastIndexOf('.');
  325. if (index < 0)
  326. return null;
  327. else
  328. return qname.substring(0, index);
  329. }
  330. /**
  331. * Sets the class name
  332. *
  333. * @param name fully-qualified name
  334. */
  335. public void setName(String name) {
  336. checkModify();
  337. if (name != null)
  338. qualifiedName = name;
  339. }
  340. /**
  341. * Returns the generic signature of the class.
  342. *
  343. * <p>The generics of Java is implemented by the erasure technique.
  344. * After compilation, all type parameters are dropped off from the
  345. * main part of a class file. However, for reflection, the type
  346. * parameters are encoded into generic signatures and attached
  347. * to a class file.
  348. *
  349. * @return null if the generic signature is not included.
  350. * @see javassist.bytecode.SignatureAttribute#toClassSignature(String)
  351. * @see CtMember#getGenericSignature()
  352. * @since 3.17
  353. */
  354. public String getGenericSignature() { return null; }
  355. /**
  356. * Sets the generic signature of the class.
  357. *
  358. * <p>The generics of Java is implemented by the erasure technique.
  359. * After compilation, all type parameters are dropped off from the
  360. * main part of a class file. However, for reflection, the type
  361. * parameters must be encoded into generic signatures and attached
  362. * to a class file.
  363. *
  364. * <p>For example,
  365. *
  366. * <pre>class List<T> {
  367. * T value;
  368. * T get() { return value; }
  369. * void set(T v) { value = v; }
  370. * }
  371. * </pre>
  372. *
  373. * <p>this class is generated by the following code:
  374. *
  375. * <pre>
  376. * ClassPool pool = ClassPool.getDefault();
  377. * CtClass cc = pool.makeClass("List");
  378. * CtClass objectClass = pool.get(CtClass.javaLangObject);
  379. * ClassSignature cs = new ClassSignature(
  380. * new TypeParameter[] { new TypeParameter("T") });
  381. * cc.setGenericSignature(cs.encode()); // &lt;T:Ljava/lang/Object;&gt;Ljava/lang/Object;
  382. *
  383. * CtField f = new CtField(objClass, "value", cc);
  384. * TypeVariable tvar = new TypeVariable("T");
  385. * f.setGenericSignature(tvar.encode()); // TT;
  386. * cc.addField(f);
  387. *
  388. * CtMethod m = CtNewMethod.make("public Object get(){return value;}", cc);
  389. * MethodSignature ms = new MethodSignature(null, null, tvar, null);
  390. * m.setGenericSignature(ms.encode()); // ()TT;
  391. * cc.addMethod(m);
  392. *
  393. * CtMethod m2 = CtNewMethod.make("public void set(Object v){value = v;}", cc);
  394. * MethodSignature ms2 = new MethodSignature(null, new Type[] { tvar },
  395. * new BaseType("void"), null);
  396. * m2.setGenericSignature(ms2.encode()); // (TT;)V;
  397. * cc.addMethod(m2);
  398. *
  399. * cc.writeFile();
  400. * </pre>
  401. *
  402. * <p>The generated class file is equivalent to the following:
  403. *
  404. * <pre>class List {
  405. * Object value;
  406. * Object get() { return value; }
  407. * void set(Object v) { value = v; }
  408. * }</pre>
  409. *
  410. * <p>but it includes generic signatures for the class, the field,
  411. * and the methods so that the type variable <code>T</code> can be
  412. * accessible through reflection.
  413. *
  414. * @param sig a generic signature.
  415. * @see javassist.bytecode.SignatureAttribute.ClassSignature#encode()
  416. * @see javassist.bytecode.SignatureAttribute.MethodSignature#encode()
  417. * @see CtMember#setGenericSignature(String)
  418. * @since 3.17
  419. */
  420. public void setGenericSignature(String sig) { checkModify(); }
  421. /**
  422. * Substitutes <code>newName</code> for all occurrences of a class
  423. * name <code>oldName</code> in the class file.
  424. *
  425. * @param oldName replaced class name
  426. * @param newName substituted class name
  427. */
  428. public void replaceClassName(String oldName, String newName) {
  429. checkModify();
  430. }
  431. /**
  432. * Changes class names appearing in the class file according to the
  433. * given <code>map</code>.
  434. *
  435. * <p>All the class names appearing in the class file are tested
  436. * with <code>map</code> to determine whether each class name is
  437. * replaced or not. Thus this method can be used for collecting
  438. * all the class names in the class file. To do that, first define
  439. * a subclass of <code>ClassMap</code> so that <code>get()</code>
  440. * records all the given parameters. Then, make an instance of
  441. * that subclass as an empty hash-table. Finally, pass that instance
  442. * to this method. After this method finishes, that instance would
  443. * contain all the class names appearing in the class file.
  444. *
  445. * @param map the hashtable associating replaced class names
  446. * with substituted names.
  447. */
  448. public void replaceClassName(ClassMap map) {
  449. checkModify();
  450. }
  451. /**
  452. * Returns a collection of the names of all the classes
  453. * referenced in this class.
  454. * That collection includes the name of this class.
  455. *
  456. * <p>This method may return <code>null</code>.
  457. *
  458. * @return a <code>Collection&lt;String&gt;</code> object.
  459. */
  460. public synchronized Collection getRefClasses() {
  461. ClassFile cf = getClassFile2();
  462. if (cf != null) {
  463. ClassMap cm = new ClassMap() {
  464. public void put(String oldname, String newname) {
  465. put0(oldname, newname);
  466. }
  467. public Object get(Object jvmClassName) {
  468. String n = toJavaName((String)jvmClassName);
  469. put0(n, n);
  470. return null;
  471. }
  472. public void fix(String name) {}
  473. };
  474. cf.getRefClasses(cm);
  475. return cm.values();
  476. }
  477. else
  478. return null;
  479. }
  480. /**
  481. * Determines whether this object represents a class or an interface.
  482. * It returns <code>true</code> if this object represents an interface.
  483. */
  484. public boolean isInterface() {
  485. return false;
  486. }
  487. /**
  488. * Determines whether this object represents an annotation type.
  489. * It returns <code>true</code> if this object represents an annotation type.
  490. *
  491. * @since 3.2
  492. */
  493. public boolean isAnnotation() {
  494. return false;
  495. }
  496. /**
  497. * Determines whether this object represents an enum.
  498. * It returns <code>true</code> if this object represents an enum.
  499. *
  500. * @since 3.2
  501. */
  502. public boolean isEnum() {
  503. return false;
  504. }
  505. /**
  506. * Returns the modifiers for this class, encoded in an integer.
  507. * For decoding, use <code>javassist.Modifier</code>.
  508. *
  509. * <p>If the class is a static nested class (a.k.a. static inner class),
  510. * the returned modifiers include <code>Modifier.STATIC</code>.
  511. *
  512. * @see Modifier
  513. */
  514. public int getModifiers() {
  515. return 0;
  516. }
  517. /**
  518. * Returns true if the class has the specified annotation class.
  519. *
  520. * @param clz the annotation class.
  521. * @return <code>true</code> if the annotation is found, otherwise <code>false</code>.
  522. * @since 3.11
  523. */
  524. public boolean hasAnnotation(Class clz) {
  525. return false;
  526. }
  527. /**
  528. * Returns the annotation if the class has the specified annotation class.
  529. * For example, if an annotation <code>@Author</code> is associated
  530. * with this class, an <code>Author</code> object is returned.
  531. * The member values can be obtained by calling methods on
  532. * the <code>Author</code> object.
  533. *
  534. * @param clz the annotation class.
  535. * @return the annotation if found, otherwise <code>null</code>.
  536. * @since 3.11
  537. */
  538. public Object getAnnotation(Class clz) throws ClassNotFoundException {
  539. return null;
  540. }
  541. /**
  542. * Returns the annotations associated with this class.
  543. * For example, if an annotation <code>@Author</code> is associated
  544. * with this class, the returned array contains an <code>Author</code>
  545. * object. The member values can be obtained by calling methods on
  546. * the <code>Author</code> object.
  547. *
  548. * @return an array of annotation-type objects.
  549. * @see CtMember#getAnnotations()
  550. * @since 3.1
  551. */
  552. public Object[] getAnnotations() throws ClassNotFoundException {
  553. return new Object[0];
  554. }
  555. /**
  556. * Returns the annotations associated with this class.
  557. * This method is equivalent to <code>getAnnotations()</code>
  558. * except that, if any annotations are not on the classpath,
  559. * they are not included in the returned array.
  560. *
  561. * @return an array of annotation-type objects.
  562. * @see #getAnnotations()
  563. * @see CtMember#getAvailableAnnotations()
  564. * @since 3.3
  565. */
  566. public Object[] getAvailableAnnotations(){
  567. return new Object[0];
  568. }
  569. /**
  570. * Returns an array of nested classes declared in the class.
  571. * Nested classes are inner classes, anonymous classes, local classes,
  572. * and static nested classes. This simply calls <code>getNestedClasses()</code>.
  573. *
  574. * @see #getNestedClasses()
  575. * @since 3.15
  576. */
  577. public CtClass[] getDeclaredClasses() throws NotFoundException {
  578. return getNestedClasses();
  579. }
  580. /**
  581. * Returns an array of nested classes declared in the class.
  582. * Nested classes are inner classes, anonymous classes, local classes,
  583. * and static nested classes.
  584. *
  585. * @since 3.2
  586. */
  587. public CtClass[] getNestedClasses() throws NotFoundException {
  588. return new CtClass[0];
  589. }
  590. /**
  591. * Sets the modifiers.
  592. *
  593. * <p>If the class is a nested class, this method also modifies
  594. * the class declaring that nested class (i.e. the enclosing
  595. * class is modified).
  596. *
  597. * @param mod modifiers encoded by
  598. * <code>javassist.Modifier</code>
  599. * @see Modifier
  600. */
  601. public void setModifiers(int mod) {
  602. checkModify();
  603. }
  604. /**
  605. * Determines whether the class directly or indirectly extends
  606. * the given class. If this class extends a class A and
  607. * the class A extends a class B, then subclassof(B) returns true.
  608. *
  609. * <p>This method returns true if the given class is identical to
  610. * the class represented by this object.
  611. */
  612. public boolean subclassOf(CtClass superclass) {
  613. return false;
  614. }
  615. /**
  616. * Obtains the class object representing the superclass of the
  617. * class.
  618. * It returns null if this object represents the
  619. * <code>java.lang.Object</code> class and thus it does not have
  620. * the super class.
  621. *
  622. * <p>If this object represents an interface, this method
  623. * always returns the <code>java.lang.Object</code> class.
  624. * To obtain the super interfaces
  625. * extended by that interface, call <code>getInterfaces()</code>.
  626. */
  627. public CtClass getSuperclass() throws NotFoundException {
  628. return null;
  629. }
  630. /**
  631. * Changes a super class unless this object represents an interface.
  632. * The new super class must be compatible with the old one; for example,
  633. * it should inherit from the old super class.
  634. *
  635. * <p>If this object represents an interface, this method is equivalent
  636. * to <code>addInterface()</code>; it appends <code>clazz</code> to
  637. * the list of the super interfaces extended by that interface.
  638. * Note that an interface can extend multiple super interfaces.
  639. *
  640. * @see #replaceClassName(String, String)
  641. * @see #replaceClassName(ClassMap)
  642. */
  643. public void setSuperclass(CtClass clazz) throws CannotCompileException {
  644. checkModify();
  645. }
  646. /**
  647. * Obtains the class objects representing the interfaces implemented
  648. * by the class or, if this object represents an interface, the interfaces
  649. * extended by that interface.
  650. */
  651. public CtClass[] getInterfaces() throws NotFoundException {
  652. return new CtClass[0];
  653. }
  654. /**
  655. * Sets implemented interfaces. If this object represents an interface,
  656. * this method sets the interfaces extended by that interface.
  657. *
  658. * @param list a list of the <code>CtClass</code> objects
  659. * representing interfaces, or
  660. * <code>null</code> if the class implements
  661. * no interfaces.
  662. */
  663. public void setInterfaces(CtClass[] list) {
  664. checkModify();
  665. }
  666. /**
  667. * Adds an interface.
  668. *
  669. * @param anInterface the added interface.
  670. */
  671. public void addInterface(CtClass anInterface) {
  672. checkModify();
  673. }
  674. /**
  675. * If this class is a member class or interface of another class,
  676. * then the class enclosing this class is returned.
  677. *
  678. * @return null if this class is a top-level class or an anonymous class.
  679. */
  680. public CtClass getDeclaringClass() throws NotFoundException {
  681. return null;
  682. }
  683. /**
  684. * Returns the immediately enclosing method of this class.
  685. * This method works only with JDK 1.5 or later.
  686. *
  687. * @return null if this class is not a local class or an anonymous
  688. * class.
  689. */
  690. public CtMethod getEnclosingMethod() throws NotFoundException {
  691. return null;
  692. }
  693. /**
  694. * Makes a new public nested class. If this method is called,
  695. * the <code>CtClass</code>, which encloses the nested class, is modified
  696. * since a class file includes a list of nested classes.
  697. *
  698. * <p>The current implementation only supports a static nested class.
  699. * <code>isStatic</code> must be true.
  700. *
  701. * @param name the simple name of the nested class.
  702. * @param isStatic true if the nested class is static.
  703. */
  704. public CtClass makeNestedClass(String name, boolean isStatic) {
  705. throw new RuntimeException(getName() + " is not a class");
  706. }
  707. /**
  708. * Returns an array containing <code>CtField</code> objects
  709. * representing all the non-private fields of the class.
  710. * That array includes non-private fields inherited from the
  711. * superclasses.
  712. */
  713. public CtField[] getFields() { return new CtField[0]; }
  714. /**
  715. * Returns the field with the specified name. The returned field
  716. * may be a private field declared in a super class or interface.
  717. */
  718. public CtField getField(String name) throws NotFoundException {
  719. return getField(name, null);
  720. }
  721. /**
  722. * Returns the field with the specified name and type. The returned field
  723. * may be a private field declared in a super class or interface.
  724. * Unlike Java, the JVM allows a class to have
  725. * multiple fields with the same name but different types.
  726. *
  727. * @param name the field name.
  728. * @param desc the type descriptor of the field. It is available by
  729. * {@link CtField#getSignature()}.
  730. * @see CtField#getSignature()
  731. */
  732. public CtField getField(String name, String desc) throws NotFoundException {
  733. throw new NotFoundException(name);
  734. }
  735. /**
  736. * @return null if the specified field is not found.
  737. */
  738. CtField getField2(String name, String desc) { return null; }
  739. /**
  740. * Gets all the fields declared in the class. The inherited fields
  741. * are not included.
  742. *
  743. * <p>Note: the result does not include inherited fields.
  744. */
  745. public CtField[] getDeclaredFields() { return new CtField[0]; }
  746. /**
  747. * Retrieves the field with the specified name among the fields
  748. * declared in the class.
  749. *
  750. * <p>Note: this method does not search the super classes.
  751. */
  752. public CtField getDeclaredField(String name) throws NotFoundException {
  753. throw new NotFoundException(name);
  754. }
  755. /**
  756. * Retrieves the field with the specified name and type among the fields
  757. * declared in the class. Unlike Java, the JVM allows a class to have
  758. * multiple fields with the same name but different types.
  759. *
  760. * <p>Note: this method does not search the super classes.
  761. *
  762. * @param name the field name.
  763. * @param desc the type descriptor of the field. It is available by
  764. * {@link CtField#getSignature()}.
  765. * @see CtField#getSignature()
  766. */
  767. public CtField getDeclaredField(String name, String desc) throws NotFoundException {
  768. throw new NotFoundException(name);
  769. }
  770. /**
  771. * Gets all the constructors and methods declared in the class.
  772. */
  773. public CtBehavior[] getDeclaredBehaviors() {
  774. return new CtBehavior[0];
  775. }
  776. /**
  777. * Returns an array containing <code>CtConstructor</code> objects
  778. * representing all the non-private constructors of the class.
  779. */
  780. public CtConstructor[] getConstructors() {
  781. return new CtConstructor[0];
  782. }
  783. /**
  784. * Returns the constructor with the given signature,
  785. * which is represented by a character string
  786. * called method descriptor.
  787. * For details of the method descriptor, see the JVM specification
  788. * or <code>javassist.bytecode.Descriptor</code>.
  789. *
  790. * @param desc method descriptor
  791. * @see javassist.bytecode.Descriptor
  792. */
  793. public CtConstructor getConstructor(String desc)
  794. throws NotFoundException
  795. {
  796. throw new NotFoundException("no such constructor");
  797. }
  798. /**
  799. * Gets all the constructors declared in the class.
  800. *
  801. * @see javassist.CtConstructor
  802. */
  803. public CtConstructor[] getDeclaredConstructors() {
  804. return new CtConstructor[0];
  805. }
  806. /**
  807. * Returns a constructor receiving the specified parameters.
  808. *
  809. * @param params parameter types.
  810. */
  811. public CtConstructor getDeclaredConstructor(CtClass[] params)
  812. throws NotFoundException
  813. {
  814. String desc = Descriptor.ofConstructor(params);
  815. return getConstructor(desc);
  816. }
  817. /**
  818. * Gets the class initializer (static constructor)
  819. * declared in the class.
  820. * This method returns <code>null</code> if
  821. * no class initializer is not declared.
  822. *
  823. * @see #makeClassInitializer()
  824. * @see javassist.CtConstructor
  825. */
  826. public CtConstructor getClassInitializer() {
  827. return null;
  828. }
  829. /**
  830. * Returns an array containing <code>CtMethod</code> objects
  831. * representing all the non-private methods of the class.
  832. * That array includes non-private methods inherited from the
  833. * superclasses.
  834. */
  835. public CtMethod[] getMethods() {
  836. return new CtMethod[0];
  837. }
  838. /**
  839. * Returns the method with the given name and signature.
  840. * The returned method may be declared in a super class.
  841. * The method signature is represented by a character string
  842. * called method descriptor,
  843. * which is defined in the JVM specification.
  844. *
  845. * @param name method name
  846. * @param desc method descriptor
  847. * @see CtBehavior#getSignature()
  848. * @see javassist.bytecode.Descriptor
  849. */
  850. public CtMethod getMethod(String name, String desc)
  851. throws NotFoundException
  852. {
  853. throw new NotFoundException(name);
  854. }
  855. /**
  856. * Gets all methods declared in the class. The inherited methods
  857. * are not included.
  858. *
  859. * @see javassist.CtMethod
  860. */
  861. public CtMethod[] getDeclaredMethods() {
  862. return new CtMethod[0];
  863. }
  864. /**
  865. * Retrieves the method with the specified name and parameter types
  866. * among the methods declared in the class.
  867. *
  868. * <p>Note: this method does not search the superclasses.
  869. *
  870. * @param name method name
  871. * @param params parameter types
  872. * @see javassist.CtMethod
  873. */
  874. public CtMethod getDeclaredMethod(String name, CtClass[] params)
  875. throws NotFoundException
  876. {
  877. throw new NotFoundException(name);
  878. }
  879. /**
  880. * Retrieves the method with the specified name among the methods
  881. * declared in the class. If there are multiple methods with
  882. * the specified name, then this method returns one of them.
  883. *
  884. * <p>Note: this method does not search the superclasses.
  885. *
  886. * @see javassist.CtMethod
  887. */
  888. public CtMethod getDeclaredMethod(String name) throws NotFoundException {
  889. throw new NotFoundException(name);
  890. }
  891. /**
  892. * Makes an empty class initializer (static constructor).
  893. * If the class already includes a class initializer,
  894. * this method returns it.
  895. *
  896. * @see #getClassInitializer()
  897. */
  898. public CtConstructor makeClassInitializer()
  899. throws CannotCompileException
  900. {
  901. throw new CannotCompileException("not a class");
  902. }
  903. /**
  904. * Adds a constructor. To add a class initializer (static constructor),
  905. * call <code>makeClassInitializer()</code>.
  906. *
  907. * @see #makeClassInitializer()
  908. */
  909. public void addConstructor(CtConstructor c)
  910. throws CannotCompileException
  911. {
  912. checkModify();
  913. }
  914. /**
  915. * Removes a constructor declared in this class.
  916. *
  917. * @param c removed constructor.
  918. * @throws NotFoundException if the constructor is not found.
  919. */
  920. public void removeConstructor(CtConstructor c) throws NotFoundException {
  921. checkModify();
  922. }
  923. /**
  924. * Adds a method.
  925. */
  926. public void addMethod(CtMethod m) throws CannotCompileException {
  927. checkModify();
  928. }
  929. /**
  930. * Removes a method declared in this class.
  931. *
  932. * @param m removed method.
  933. * @throws NotFoundException if the method is not found.
  934. */
  935. public void removeMethod(CtMethod m) throws NotFoundException {
  936. checkModify();
  937. }
  938. /**
  939. * Adds a field.
  940. *
  941. * <p>The <code>CtField</code> belonging to another
  942. * <code>CtClass</code> cannot be directly added to this class.
  943. * Only a field created for this class can be added.
  944. *
  945. * @see javassist.CtField#CtField(CtField,CtClass)
  946. */
  947. public void addField(CtField f) throws CannotCompileException {
  948. addField(f, (CtField.Initializer)null);
  949. }
  950. /**
  951. * Adds a field with an initial value.
  952. *
  953. * <p>The <code>CtField</code> belonging to another
  954. * <code>CtClass</code> cannot be directly added to this class.
  955. * Only a field created for this class can be added.
  956. *
  957. * <p>The initial value is given as an expression written in Java.
  958. * Any regular Java expression can be used for specifying the initial
  959. * value. The followings are examples.
  960. *
  961. * <ul><pre>
  962. * cc.addField(f, "0") // the initial value is 0.
  963. * cc.addField(f, "i + 1") // i + 1.
  964. * cc.addField(f, "new Point()"); // a Point object.
  965. * </pre></ul>
  966. *
  967. * <p>Here, the type of variable <code>cc</code> is <code>CtClass</code>.
  968. * The type of <code>f</code> is <code>CtField</code>.
  969. *
  970. * <p>Note: do not change the modifier of the field
  971. * (in particular, do not add or remove <code>static</code>
  972. * to/from the modifier)
  973. * after it is added to the class by <code>addField()</code>.
  974. *
  975. * @param init an expression for the initial value.
  976. *
  977. * @see javassist.CtField.Initializer#byExpr(String)
  978. * @see javassist.CtField#CtField(CtField,CtClass)
  979. */
  980. public void addField(CtField f, String init)
  981. throws CannotCompileException
  982. {
  983. checkModify();
  984. }
  985. /**
  986. * Adds a field with an initial value.
  987. *
  988. * <p>The <code>CtField</code> belonging to another
  989. * <code>CtClass</code> cannot be directly added to this class.
  990. * Only a field created for this class can be added.
  991. *
  992. * <p>For example,
  993. *
  994. * <ul><pre>
  995. * CtClass cc = ...;
  996. * addField(new CtField(CtClass.intType, "i", cc),
  997. * CtField.Initializer.constant(1));
  998. * </pre></ul>
  999. *
  1000. * <p>This code adds an <code>int</code> field named "i". The
  1001. * initial value of this field is 1.
  1002. *
  1003. * @param init specifies the initial value of the field.
  1004. *
  1005. * @see javassist.CtField#CtField(CtField,CtClass)
  1006. */
  1007. public void addField(CtField f, CtField.Initializer init)
  1008. throws CannotCompileException
  1009. {
  1010. checkModify();
  1011. }
  1012. /**
  1013. * Removes a field declared in this class.
  1014. *
  1015. * @param f removed field.
  1016. * @throws NotFoundException if the field is not found.
  1017. */
  1018. public void removeField(CtField f) throws NotFoundException {
  1019. checkModify();
  1020. }
  1021. /**
  1022. * Obtains an attribute with the given name.
  1023. * If that attribute is not found in the class file, this
  1024. * method returns null.
  1025. *
  1026. * <p>This is a convenient method mainly for obtaining
  1027. * a user-defined attribute. For dealing with attributes, see the
  1028. * <code>javassist.bytecode</code> package. For example, the following
  1029. * expression returns all the attributes of a class file.
  1030. *
  1031. * <ul><pre>
  1032. * getClassFile().getAttributes()
  1033. * </pre></ul>
  1034. *
  1035. * @param name attribute name
  1036. * @see javassist.bytecode.AttributeInfo
  1037. */
  1038. public byte[] getAttribute(String name) {
  1039. return null;
  1040. }
  1041. /**
  1042. * Adds a named attribute.
  1043. * An arbitrary data (smaller than 64Kb) can be saved in the class
  1044. * file. Some attribute name are reserved by the JVM.
  1045. * The attributes with the non-reserved names are ignored when a
  1046. * class file is loaded into the JVM.
  1047. * If there is already an attribute with
  1048. * the same name, this method substitutes the new one for it.
  1049. *
  1050. * <p>This is a convenient method mainly for adding
  1051. * a user-defined attribute. For dealing with attributes, see the
  1052. * <code>javassist.bytecode</code> package. For example, the following
  1053. * expression adds an attribute <code>info</code> to a class file.
  1054. *
  1055. * <ul><pre>
  1056. * getClassFile().addAttribute(info)
  1057. * </pre></ul>
  1058. *
  1059. * @param name attribute name
  1060. * @param data attribute value
  1061. * @see javassist.bytecode.AttributeInfo
  1062. */
  1063. public void setAttribute(String name, byte[] data) {
  1064. checkModify();
  1065. }
  1066. /**
  1067. * Applies the given converter to all methods and constructors
  1068. * declared in the class. This method calls <code>instrument()</code>
  1069. * on every <code>CtMethod</code> and <code>CtConstructor</code> object
  1070. * in the class.
  1071. *
  1072. * @param converter specifies how to modify.
  1073. */
  1074. public void instrument(CodeConverter converter)
  1075. throws CannotCompileException
  1076. {
  1077. checkModify();
  1078. }
  1079. /**
  1080. * Modifies the bodies of all methods and constructors
  1081. * declared in the class. This method calls <code>instrument()</code>
  1082. * on every <code>CtMethod</code> and <code>CtConstructor</code> object
  1083. * in the class.
  1084. *
  1085. * @param editor specifies how to modify.
  1086. */
  1087. public void instrument(ExprEditor editor)
  1088. throws CannotCompileException
  1089. {
  1090. checkModify();
  1091. }
  1092. /**
  1093. * Converts this class to a <code>java.lang.Class</code> object.
  1094. * Once this method is called, further modifications are not
  1095. * allowed any more.
  1096. * To load the class, this method uses the context class loader
  1097. * of the current thread. If the program is running on some application
  1098. * server, the context class loader might be inappropriate to load the
  1099. * class.
  1100. *
  1101. * <p>This method is provided for convenience. If you need more
  1102. * complex functionality, you should write your own class loader.
  1103. *
  1104. * <p>Note: this method calls <code>toClass()</code>
  1105. * in <code>ClassPool</code>.
  1106. *
  1107. * <p><b>Warining:</b> A Class object returned by this method may not
  1108. * work with a security manager or a signed jar file because a
  1109. * protection domain is not specified.
  1110. *
  1111. * @see #toClass(java.lang.ClassLoader,ProtectionDomain)
  1112. * @see ClassPool#toClass(CtClass)
  1113. */
  1114. public Class toClass() throws CannotCompileException {
  1115. return getClassPool().toClass(this);
  1116. }
  1117. /**
  1118. * Converts this class to a <code>java.lang.Class</code> object.
  1119. * Once this method is called, further modifications are not allowed
  1120. * any more.
  1121. *
  1122. * <p>The class file represented by this <code>CtClass</code> is
  1123. * loaded by the given class loader to construct a
  1124. * <code>java.lang.Class</code> object. Since a private method
  1125. * on the class loader is invoked through the reflection API,
  1126. * the caller must have permissions to do that.
  1127. *
  1128. * <p>An easy way to obtain <code>ProtectionDomain</code> object is
  1129. * to call <code>getProtectionDomain()</code>
  1130. * in <code>java.lang.Class</code>. It returns the domain that
  1131. * the class belongs to.
  1132. *
  1133. * <p>This method is provided for convenience. If you need more
  1134. * complex functionality, you should write your own class loader.
  1135. *
  1136. * <p>Note: this method calls <code>toClass()</code>
  1137. * in <code>ClassPool</code>.
  1138. *
  1139. * @param loader the class loader used to load this class.
  1140. * If it is null, the class loader returned by
  1141. * {@link ClassPool#getClassLoader()} is used.
  1142. * @param domain the protection domain that the class belongs to.
  1143. * If it is null, the default domain created
  1144. * by <code>java.lang.ClassLoader</code> is used.
  1145. * @see ClassPool#toClass(CtClass,java.lang.ClassLoader)
  1146. * @since 3.3
  1147. */
  1148. public Class toClass(ClassLoader loader, ProtectionDomain domain)
  1149. throws CannotCompileException
  1150. {
  1151. ClassPool cp = getClassPool();
  1152. if (loader == null)
  1153. loader = cp.getClassLoader();
  1154. return cp.toClass(this, loader, domain);
  1155. }
  1156. /**
  1157. * Converts this class to a <code>java.lang.Class</code> object.
  1158. *
  1159. * <p><b>Warining:</b> A Class object returned by this method may not
  1160. * work with a security manager or a signed jar file because a
  1161. * protection domain is not specified.
  1162. *
  1163. * @deprecated Replaced by {@link #toClass(ClassLoader,ProtectionDomain)}
  1164. */
  1165. public final Class toClass(ClassLoader loader)
  1166. throws CannotCompileException
  1167. {
  1168. return getClassPool().toClass(this, loader);
  1169. }
  1170. /**
  1171. * Removes this <code>CtClass</code> object from the
  1172. * <code>ClassPool</code>.
  1173. * After this method is called, any method cannot be called on the
  1174. * removed <code>CtClass</code> object.
  1175. *
  1176. * <p>If <code>get()</code> in <code>ClassPool</code> is called
  1177. * with the name of the removed method,
  1178. * the <code>ClassPool</code> will read the class file again
  1179. * and constructs another <code>CtClass</code> object representing
  1180. * the same class.
  1181. */
  1182. public void detach() {
  1183. ClassPool cp = getClassPool();
  1184. CtClass obj = cp.removeCached(getName());
  1185. if (obj != this)
  1186. cp.cacheCtClass(getName(), obj, false);
  1187. }
  1188. /**
  1189. * Disallows (or allows) automatically pruning this <code>CtClass</code>
  1190. * object.
  1191. *
  1192. * <p>
  1193. * Javassist can automatically prune a <code>CtClass</code> object
  1194. * when <code>toBytecode()</code> (or <code>toClass()</code>,
  1195. * <code>writeFile()</code>) is called.
  1196. * Since a <code>ClassPool</code> holds all instances of <code>CtClass</code>
  1197. * even after <code>toBytecode()</code> (or <code>toClass()</code>,
  1198. * <code>writeFile()</code>) is called, pruning may significantly
  1199. * save memory consumption.
  1200. *
  1201. * <p>If <code>ClassPool.doPruning</code> is true, the automatic pruning
  1202. * is on by default. Otherwise, it is off. The default value of
  1203. * <code>ClassPool.doPruning</code> is false.
  1204. *
  1205. * @param stop disallow pruning if true. Otherwise, allow.
  1206. * @return the previous status of pruning. true if pruning is already stopped.
  1207. *
  1208. * @see #detach()
  1209. * @see #prune()
  1210. * @see ClassPool#doPruning
  1211. */
  1212. public boolean stopPruning(boolean stop) { return true; }
  1213. /**
  1214. * Discards unnecessary attributes, in particular,
  1215. * <code>CodeAttribute</code>s (method bodies) of the class,
  1216. * to minimize the memory footprint.
  1217. * After calling this method, the class is read only.
  1218. * It cannot be modified any more.
  1219. * Furthermore, <code>toBytecode()</code>,
  1220. * <code>writeFile()</code>, <code>toClass()</code>,
  1221. * or <code>instrument()</code> cannot be called.
  1222. * However, the method names and signatures in the class etc.
  1223. * are still accessible.
  1224. *
  1225. * <p><code>toBytecode()</code>, <code>writeFile()</code>, and
  1226. * <code>toClass()</code> internally call this method if
  1227. * automatic pruning is on.
  1228. *
  1229. * <p>According to some experiments, pruning does not really reduce
  1230. * memory consumption. Only about 20%. Since pruning takes time,
  1231. * it might not pay off. So the automatic pruning is off by default.
  1232. *
  1233. * @see #stopPruning(boolean)
  1234. * @see #detach()
  1235. * @see ClassPool#doPruning
  1236. *
  1237. * @see #toBytecode()
  1238. * @see #toClass()
  1239. * @see #writeFile()
  1240. * @see #instrument(CodeConverter)
  1241. * @see #instrument(ExprEditor)
  1242. */
  1243. public void prune() {}
  1244. /* Called by get() in ClassPool.
  1245. * CtClassType overrides this method.
  1246. */
  1247. void incGetCounter() {}
  1248. /**
  1249. * If this method is called, the class file will be
  1250. * rebuilt when it is finally generated by
  1251. * <code>toBytecode()</code> and <code>writeFile()</code>.
  1252. * For a performance reason, the symbol table of the
  1253. * class file may contain unused entries, for example,
  1254. * after a method or a filed is deleted.
  1255. * This method
  1256. * removes those unused entries. This removal will
  1257. * minimize the size of the class file.
  1258. *
  1259. * @since 3.8.1
  1260. */
  1261. public void rebuildClassFile() {}
  1262. /**
  1263. * Converts this class to a class file.
  1264. * Once this method is called, further modifications are not
  1265. * possible any more.
  1266. *
  1267. * @return the contents of the class file.
  1268. */
  1269. public byte[] toBytecode() throws IOException, CannotCompileException {
  1270. ByteArrayOutputStream barray = new ByteArrayOutputStream();
  1271. DataOutputStream out = new DataOutputStream(barray);
  1272. try {
  1273. toBytecode(out);
  1274. }
  1275. finally {
  1276. out.close();
  1277. }
  1278. return barray.toByteArray();
  1279. }
  1280. /**
  1281. * Writes a class file represented by this <code>CtClass</code>
  1282. * object in the current directory.
  1283. * Once this method is called, further modifications are not
  1284. * possible any more.
  1285. *
  1286. * @see #debugWriteFile()
  1287. */
  1288. public void writeFile()
  1289. throws NotFoundException, IOException, CannotCompileException
  1290. {
  1291. writeFile(".");
  1292. }
  1293. /**
  1294. * Writes a class file represented by this <code>CtClass</code>
  1295. * object on a local disk.
  1296. * Once this method is called, further modifications are not
  1297. * possible any more.
  1298. *
  1299. * @param directoryName it must end without a directory separator.
  1300. * @see #debugWriteFile(String)
  1301. */
  1302. public void writeFile(String directoryName)
  1303. throws CannotCompileException, IOException
  1304. {
  1305. DataOutputStream out = makeFileOutput(directoryName);
  1306. try {
  1307. toBytecode(out);
  1308. }
  1309. finally {
  1310. out.close();
  1311. }
  1312. }
  1313. protected DataOutputStream makeFileOutput(String directoryName) {
  1314. String classname = getName();
  1315. String filename = directoryName + File.separatorChar
  1316. + classname.replace('.', File.separatorChar) + ".class";
  1317. int pos = filename.lastIndexOf(File.separatorChar);
  1318. if (pos > 0) {
  1319. String dir = filename.substring(0, pos);
  1320. if (!dir.equals("."))
  1321. new File(dir).mkdirs();
  1322. }
  1323. return new DataOutputStream(new BufferedOutputStream(
  1324. new DelayedFileOutputStream(filename)));
  1325. }
  1326. /**
  1327. * Writes a class file as <code>writeFile()</code> does although this
  1328. * method does not prune or freeze the class after writing the class
  1329. * file. Note that, once <code>writeFile()</code> or <code>toBytecode()</code>
  1330. * is called, it cannot be called again since the class is pruned and frozen.
  1331. * This method would be useful for debugging.
  1332. */
  1333. public void debugWriteFile() {
  1334. debugWriteFile(".");
  1335. }
  1336. /**
  1337. * Writes a class file as <code>writeFile()</code> does although this
  1338. * method does not prune or freeze the class after writing the class
  1339. * file. Note that, once <code>writeFile()</code> or <code>toBytecode()</code>
  1340. * is called, it cannot be called again since the class is pruned and frozen.
  1341. * This method would be useful for debugging.
  1342. *
  1343. * @param directoryName it must end without a directory separator.
  1344. */
  1345. public void debugWriteFile(String directoryName) {
  1346. try {
  1347. boolean p = stopPruning(true);
  1348. writeFile(directoryName);
  1349. defrost();
  1350. stopPruning(p);
  1351. }
  1352. catch (Exception e) {
  1353. throw new RuntimeException(e);
  1354. }
  1355. }
  1356. static class DelayedFileOutputStream extends OutputStream {
  1357. private FileOutputStream file;
  1358. private String filename;
  1359. DelayedFileOutputStream(String name) {
  1360. file = null;
  1361. filename = name;
  1362. }
  1363. private void init() throws IOException {
  1364. if (file == null)
  1365. file = new FileOutputStream(filename);
  1366. }
  1367. public void write(int b) throws IOException {
  1368. init();
  1369. file.write(b);
  1370. }
  1371. public void write(byte[] b) throws IOException {
  1372. init();
  1373. file.write(b);
  1374. }
  1375. public void write(byte[] b, int off, int len) throws IOException {
  1376. init();
  1377. file.write(b, off, len);
  1378. }
  1379. public void flush() throws IOException {
  1380. init();
  1381. file.flush();
  1382. }
  1383. public void close() throws IOException {
  1384. init();
  1385. file.close();
  1386. }
  1387. }
  1388. /**
  1389. * Converts this class to a class file.
  1390. * Once this method is called, further modifications are not
  1391. * possible any more.
  1392. *
  1393. * <p>This method dose not close the output stream in the end.
  1394. *
  1395. * @param out the output stream that a class file is written to.
  1396. */
  1397. public void toBytecode(DataOutputStream out)
  1398. throws CannotCompileException, IOException
  1399. {
  1400. throw new CannotCompileException("not a class");
  1401. }
  1402. /**
  1403. * Makes a unique member name. This method guarantees that
  1404. * the returned name is not used as a prefix of any methods
  1405. * or fields visible in this class.
  1406. * If the returned name is XYZ, then any method or field names
  1407. * in this class do not start with XYZ.
  1408. *
  1409. * @param prefix the prefix of the member name.
  1410. */
  1411. public String makeUniqueName(String prefix) {
  1412. throw new RuntimeException("not available in " + getName());
  1413. }
  1414. /* Invoked from ClassPool#compress().
  1415. * This method is overridden by CtClassType.
  1416. */
  1417. void compress() {}
  1418. }