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

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