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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236
  1. /*
  2. * Javassist, a Java-bytecode translator toolkit.
  3. * Copyright (C) 1999-2005 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.1RC2";
  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-2005 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. * @see Modifier
  385. */
  386. public int getModifiers() {
  387. return 0;
  388. }
  389. /**
  390. * Returns the annotations associated with this class.
  391. * For example, if an annotation <code>@Author</code> is associated
  392. * with this class, the returned array contains an <code>Author</code>
  393. * object. The member values can be obtained by calling methods on
  394. * the <code>Author</code> object.
  395. *
  396. * @return an array of annotation-type objects.
  397. * @since 3.1
  398. */
  399. public Object[] getAnnotations() throws ClassNotFoundException {
  400. return new Object[0];
  401. }
  402. /**
  403. * Sets the modifiers.
  404. *
  405. * <p>If the class is a nested class, this method also modifies
  406. * the class declaring that nested class (i.e. the enclosing
  407. * class is modified).
  408. *
  409. * @param mod modifiers encoded by
  410. * <code>javassist.Modifier</code>
  411. * @see Modifier
  412. */
  413. public void setModifiers(int mod) {
  414. checkModify();
  415. }
  416. /**
  417. * Determines whether the class directly or indirectly extends
  418. * the given class. If this class extends a class A and
  419. * the class A extends a class B, then subclassof(B) returns true.
  420. *
  421. * <p>This method returns true if the given class is identical to
  422. * the class represented by this object.
  423. */
  424. public boolean subclassOf(CtClass superclass) {
  425. return false;
  426. }
  427. /**
  428. * Obtains the class object representing the superclass of the
  429. * class.
  430. * It returns null if this object represents the
  431. * <code>java.lang.Object</code> class and thus it does not have
  432. * the super class.
  433. *
  434. * <p>If this object represents an interface, this method
  435. * always returns the <code>java.lang.Object</code> class.
  436. * To obtain the super interfaces
  437. * extended by that interface, call <code>getInterfaces()</code>.
  438. */
  439. public CtClass getSuperclass() throws NotFoundException {
  440. return null;
  441. }
  442. /**
  443. * Changes a super class unless this object represents an interface.
  444. * The new super class must be compatible with the old one.
  445. *
  446. * <p>If this object represents an interface, this method is equivalent
  447. * to <code>addInterface()</code>; it appends <code>clazz</code> to
  448. * the list of the super interfaces extended by that interface.
  449. * Note that an interface can extend multiple super interfaces.
  450. */
  451. public void setSuperclass(CtClass clazz) throws CannotCompileException {
  452. checkModify();
  453. }
  454. /**
  455. * Obtains the class objects representing the interfaces implemented
  456. * by the class or, if this object represents an interface, the interfaces
  457. * extended by that interface.
  458. */
  459. public CtClass[] getInterfaces() throws NotFoundException {
  460. return new CtClass[0];
  461. }
  462. /**
  463. * Sets implemented interfaces. If this object represents an interface,
  464. * this method sets the interfaces extended by that interface.
  465. *
  466. * @param list a list of the <code>CtClass</code> objects
  467. * representing interfaces, or
  468. * <code>null</code> if the class implements
  469. * no interfaces.
  470. */
  471. public void setInterfaces(CtClass[] list) {
  472. checkModify();
  473. }
  474. /**
  475. * Adds an interface.
  476. *
  477. * @param anInterface the added interface.
  478. */
  479. public void addInterface(CtClass anInterface) {
  480. checkModify();
  481. }
  482. /**
  483. * If this class is a member class or interface of another class,
  484. * then the class enclosing this class is returned.
  485. *
  486. * @return null if this class is a top-level class or an anonymous class.
  487. */
  488. public CtClass getDeclaringClass() throws NotFoundException {
  489. return null;
  490. }
  491. /**
  492. * Returns the immediately enclosing method of this class.
  493. * This method works only with JDK 1.5 or later.
  494. *
  495. * @return null if this class is not a local class or an anonymous
  496. * class.
  497. */
  498. public CtMethod getEnclosingMethod() throws NotFoundException {
  499. return null;
  500. }
  501. /**
  502. * Makes a new public nested class. If this method is called,
  503. * the <code>CtClass</code>, which encloses the nested class, is modified
  504. * since a class file includes a list of inner classes.
  505. *
  506. * <p>The current implementation only supports a static nested class.
  507. * <code>isStatic</code> must be true.
  508. *
  509. * @param name the simple name of the nested class.
  510. * @param isStatic true if the nested class is static.
  511. */
  512. public CtClass makeNestedClass(String name, boolean isStatic) {
  513. throw new RuntimeException(getName() + " is not a class");
  514. }
  515. /**
  516. * Returns an array containing <code>CtField</code> objects
  517. * representing all the non-private fields of the class.
  518. * That array includes non-private fields inherited from the
  519. * superclasses.
  520. */
  521. public CtField[] getFields() { return new CtField[0]; }
  522. /**
  523. * Returns the field with the specified name. The returned field
  524. * may be a private field declared in a super class or interface.
  525. */
  526. public CtField getField(String name) throws NotFoundException {
  527. throw new NotFoundException(name);
  528. }
  529. /**
  530. * @return null if the specified field is not found.
  531. */
  532. CtField getField2(String name) { return null; }
  533. /**
  534. * Gets all the fields declared in the class. The inherited fields
  535. * are not included.
  536. *
  537. * <p>Note: the result does not include inherited fields.
  538. */
  539. public CtField[] getDeclaredFields() { return new CtField[0]; }
  540. /**
  541. * Retrieves the field with the specified name among the fields
  542. * declared in the class.
  543. *
  544. * <p>Note: this method does not search the superclasses.
  545. */
  546. public CtField getDeclaredField(String name) throws NotFoundException {
  547. throw new NotFoundException(name);
  548. }
  549. /**
  550. * Gets all the constructors and methods declared in the class.
  551. */
  552. public CtBehavior[] getDeclaredBehaviors() {
  553. return new CtBehavior[0];
  554. }
  555. /**
  556. * Returns an array containing <code>CtConstructor</code> objects
  557. * representing all the non-private constructors of the class.
  558. */
  559. public CtConstructor[] getConstructors() {
  560. return new CtConstructor[0];
  561. }
  562. /**
  563. * Returns the constructor with the given signature,
  564. * which is represented by a character string
  565. * called method descriptor.
  566. * For details of the method descriptor, see the JVM specification
  567. * or <code>javassist.bytecode.Descriptor</code>.
  568. *
  569. * @param desc method descriptor
  570. * @see javassist.bytecode.Descriptor
  571. */
  572. public CtConstructor getConstructor(String desc)
  573. throws NotFoundException
  574. {
  575. throw new NotFoundException("no such a constructor");
  576. }
  577. /**
  578. * Gets all the constructors declared in the class.
  579. *
  580. * @see javassist.CtConstructor
  581. */
  582. public CtConstructor[] getDeclaredConstructors() {
  583. return new CtConstructor[0];
  584. }
  585. /**
  586. * Returns a constructor receiving the specified parameters.
  587. *
  588. * @param params parameter types.
  589. */
  590. public CtConstructor getDeclaredConstructor(CtClass[] params)
  591. throws NotFoundException
  592. {
  593. String desc = Descriptor.ofConstructor(params);
  594. return getConstructor(desc);
  595. }
  596. /**
  597. * Gets the class initializer (static constructor)
  598. * declared in the class.
  599. * This method returns <code>null</code> if
  600. * no class initializer is not declared.
  601. *
  602. * @see #makeClassInitializer()
  603. * @see javassist.CtConstructor
  604. */
  605. public CtConstructor getClassInitializer() {
  606. return null;
  607. }
  608. /**
  609. * Returns an array containing <code>CtMethod</code> objects
  610. * representing all the non-private methods of the class.
  611. * That array includes pon-private methods inherited from the
  612. * superclasses.
  613. */
  614. public CtMethod[] getMethods() {
  615. return new CtMethod[0];
  616. }
  617. /**
  618. * Returns the method with the given name and signature.
  619. * The returned method may be declared in a super class.
  620. * The method signature is represented by a character string
  621. * called method descriptor,
  622. * which is defined in the JVM specification.
  623. *
  624. * @param name method name
  625. * @param desc method descriptor
  626. * @see CtBehavior#getSignature()
  627. * @see javassist.bytecode.Descriptor
  628. */
  629. public CtMethod getMethod(String name, String desc)
  630. throws NotFoundException
  631. {
  632. throw new NotFoundException(name);
  633. }
  634. /**
  635. * Gets all methods declared in the class. The inherited methods
  636. * are not included.
  637. *
  638. * @see javassist.CtMethod
  639. */
  640. public CtMethod[] getDeclaredMethods() {
  641. return new CtMethod[0];
  642. }
  643. /**
  644. * Retrieves the method with the specified name and parameter types
  645. * among the methods declared in the class.
  646. *
  647. * <p>Note: this method does not search the superclasses.
  648. *
  649. * @param name method name
  650. * @param params parameter types
  651. * @see javassist.CtMethod
  652. */
  653. public CtMethod getDeclaredMethod(String name, CtClass[] params)
  654. throws NotFoundException
  655. {
  656. throw new NotFoundException(name);
  657. }
  658. /**
  659. * Retrieves the method with the specified name among the methods
  660. * declared in the class. If there are multiple methods with
  661. * the specified name, then this method returns one of them.
  662. *
  663. * <p>Note: this method does not search the superclasses.
  664. *
  665. * @see javassist.CtMethod
  666. */
  667. public CtMethod getDeclaredMethod(String name) throws NotFoundException {
  668. throw new NotFoundException(name);
  669. }
  670. /**
  671. * Makes an empty class initializer (static constructor).
  672. * If the class already includes a class initializer,
  673. * this method returns it.
  674. *
  675. * @see #getClassInitializer()
  676. */
  677. public CtConstructor makeClassInitializer()
  678. throws CannotCompileException
  679. {
  680. throw new CannotCompileException("not a class");
  681. }
  682. /**
  683. * Adds a constructor. To add a class initializer (static constructor),
  684. * call <code>makeClassInitializer()</code>.
  685. *
  686. * @see #makeClassInitializer()
  687. */
  688. public void addConstructor(CtConstructor c)
  689. throws CannotCompileException
  690. {
  691. checkModify();
  692. }
  693. /**
  694. * Removes a constructor declared in this class.
  695. *
  696. * @param c removed constructor.
  697. * @throws NotFoundException if the constructor is not found.
  698. */
  699. public void removeConstructor(CtConstructor c) throws NotFoundException {
  700. checkModify();
  701. }
  702. /**
  703. * Adds a method.
  704. */
  705. public void addMethod(CtMethod m) throws CannotCompileException {
  706. checkModify();
  707. }
  708. /**
  709. * Removes a method declared in this class.
  710. *
  711. * @param m removed method.
  712. * @throws NotFoundException if the method is not found.
  713. */
  714. public void removeMethod(CtMethod m) throws NotFoundException {
  715. checkModify();
  716. }
  717. /**
  718. * Adds a field.
  719. *
  720. * <p>The <code>CtField</code> belonging to another
  721. * <code>CtClass</code> cannot be directly added to this class.
  722. * Only a field created for this class can be added.
  723. *
  724. * @see javassist.CtField#CtField(CtField,CtClass)
  725. */
  726. public void addField(CtField f) throws CannotCompileException {
  727. addField(f, (CtField.Initializer)null);
  728. }
  729. /**
  730. * Adds a field with an initial value.
  731. *
  732. * <p>The <code>CtField</code> belonging to another
  733. * <code>CtClass</code> cannot be directly added to this class.
  734. * Only a field created for this class can be added.
  735. *
  736. * <p>The initial value is given as an expression written in Java.
  737. * Any regular Java expression can be used for specifying the initial
  738. * value. The followings are examples.
  739. *
  740. * <ul><pre>
  741. * cc.addField(f, "0") // the initial value is 0.
  742. * cc.addField(f, "i + 1") // i + 1.
  743. * cc.addField(f, "new Point()"); // a Point object.
  744. * </pre></ul>
  745. *
  746. * <p>Here, the type of variable <code>cc</code> is <code>CtClass</code>.
  747. * The type of <code>f</code> is <code>CtField</code>.
  748. *
  749. * @param init an expression for the initial value.
  750. *
  751. * @see javassist.CtField.Initializer#byExpr(String)
  752. * @see javassist.CtField#CtField(CtField,CtClass)
  753. */
  754. public void addField(CtField f, String init)
  755. throws CannotCompileException
  756. {
  757. checkModify();
  758. }
  759. /**
  760. * Adds a field with an initial value.
  761. *
  762. * <p>The <code>CtField</code> belonging to another
  763. * <code>CtClass</code> cannot be directly added to this class.
  764. * Only a field created for this class can be added.
  765. *
  766. * <p>For example,
  767. *
  768. * <ul><pre>
  769. * CtClass cc = ...;
  770. * addField(new CtField(CtClass.intType, "i", cc),
  771. * CtField.Initializer.constant(1));
  772. * </pre></ul>
  773. *
  774. * <p>This code adds an <code>int</code> field named "i". The
  775. * initial value of this field is 1.
  776. *
  777. * @param init specifies the initial value of the field.
  778. *
  779. * @see javassist.CtField#CtField(CtField,CtClass)
  780. */
  781. public void addField(CtField f, CtField.Initializer init)
  782. throws CannotCompileException
  783. {
  784. checkModify();
  785. }
  786. /**
  787. * Removes a field declared in this class.
  788. *
  789. * @param f removed field.
  790. * @throws NotFoundException if the field is not found.
  791. */
  792. public void removeField(CtField f) throws NotFoundException {
  793. checkModify();
  794. }
  795. /**
  796. * Obtains an attribute with the given name.
  797. * If that attribute is not found in the class file, this
  798. * method returns null.
  799. *
  800. * <p>This is a convenient method mainly for obtaining
  801. * a user-defined attribute. For dealing with attributes, see the
  802. * <code>javassist.bytecode</code> package. For example, the following
  803. * expression returns all the attributes of a class file.
  804. *
  805. * <ul><pre>
  806. * getClassFile().getAttributes()
  807. * </pre></ul>
  808. *
  809. * @param name attribute name
  810. * @see javassist.bytecode.AttributeInfo
  811. */
  812. public byte[] getAttribute(String name) {
  813. return null;
  814. }
  815. /**
  816. * Adds a named attribute.
  817. * An arbitrary data (smaller than 64Kb) can be saved in the class
  818. * file. Some attribute name are reserved by the JVM.
  819. * The attributes with the non-reserved names are ignored when a
  820. * class file is loaded into the JVM.
  821. * If there is already an attribute with
  822. * the same name, this method substitutes the new one for it.
  823. *
  824. * <p>This is a convenient method mainly for adding
  825. * a user-defined attribute. For dealing with attributes, see the
  826. * <code>javassist.bytecode</code> package. For example, the following
  827. * expression adds an attribute <code>info</code> to a class file.
  828. *
  829. * <ul><pre>
  830. * getClassFile().addAttribute(info)
  831. * </pre></ul>
  832. *
  833. * @param name attribute name
  834. * @param data attribute value
  835. * @see javassist.bytecode.AttributeInfo
  836. */
  837. public void setAttribute(String name, byte[] data) {
  838. checkModify();
  839. }
  840. /**
  841. * Applies the given converter to all methods and constructors
  842. * declared in the class. This method calls <code>instrument()</code>
  843. * on every <code>CtMethod</code> and <code>CtConstructor</code> object
  844. * in the class.
  845. *
  846. * @param converter specifies how to modify.
  847. */
  848. public void instrument(CodeConverter converter)
  849. throws CannotCompileException
  850. {
  851. checkModify();
  852. }
  853. /**
  854. * Modifies the bodies of all methods and constructors
  855. * declared in the class. This method calls <code>instrument()</code>
  856. * on every <code>CtMethod</code> and <code>CtConstructor</code> object
  857. * in the class.
  858. *
  859. * @param editor specifies how to modify.
  860. */
  861. public void instrument(ExprEditor editor)
  862. throws CannotCompileException
  863. {
  864. checkModify();
  865. }
  866. /**
  867. * Converts this class to a <code>java.lang.Class</code> object.
  868. * Once this method is called, further modifications are not
  869. * allowed any more.
  870. * To load the class, this method uses the context class loader
  871. * of the current thread. If the program is running on some application
  872. * server, the context class loader might be inappropriate to load the
  873. * class.
  874. *
  875. * <p>This method is provided for convenience. If you need more
  876. * complex functionality, you should write your own class loader.
  877. *
  878. * <p>Note: this method calls <code>toClass()</code>
  879. * in <code>ClassPool</code>.
  880. *
  881. * @see #toClass(java.lang.ClassLoader)
  882. * @see ClassPool#toClass(CtClass)
  883. */
  884. public Class toClass() throws CannotCompileException {
  885. return getClassPool().toClass(this);
  886. }
  887. /**
  888. * Converts this class to a <code>java.lang.Class</code> object.
  889. * Once this method is called, further modifications are not allowed
  890. * any more.
  891. *
  892. * <p>The class file represented by this <code>CtClass</code> is
  893. * loaded by the given class loader to construct a
  894. * <code>java.lang.Class</code> object. Since a private method
  895. * on the class loader is invoked through the reflection API,
  896. * the caller must have permissions to do that.
  897. *
  898. * <p>This method is provided for convenience. If you need more
  899. * complex functionality, you should write your own class loader.
  900. *
  901. * <p>Note: this method calls <code>toClass()</code>
  902. * in <code>ClassPool</code>.
  903. *
  904. * @param loader the class loader used to load this class.
  905. * @see ClassPool#toClass(CtClass,java.lang.ClassLoader)
  906. */
  907. public Class toClass(ClassLoader loader)
  908. throws CannotCompileException
  909. {
  910. return getClassPool().toClass(this, loader);
  911. }
  912. /**
  913. * Removes this <code>CtClass</code> object from the
  914. * <code>ClassPool</code>.
  915. * After this method is called, any method cannot be called on the
  916. * removed <code>CtClass</code> object.
  917. *
  918. * <p>If <code>get()</code> in <code>ClassPool</code> is called
  919. * with the name of the removed method,
  920. * the <code>ClassPool</code> will read the class file again
  921. * and constructs another <code>CtClass</code> object representing
  922. * the same class.
  923. */
  924. public void detach() {
  925. ClassPool cp = getClassPool();
  926. CtClass obj = cp.removeCached(getName());
  927. if (obj != this)
  928. cp.cacheCtClass(getName(), obj, false);
  929. }
  930. /**
  931. * Disallows (or allows) automatically pruning this <code>CtClass</code>
  932. * object.
  933. *
  934. * <p>
  935. * Javassist can automatically prune a <code>CtClass</code> object
  936. * when <code>toBytecode()</code> (or <code>toClass()</code>,
  937. * <code>writeFile()</code>) is called.
  938. * Since a <code>ClassPool</code> holds all instances of <code>CtClass</code>
  939. * even after <code>toBytecode()</code> (or <code>toClass()</code>,
  940. * <code>writeFile()</code>) is called, pruning may significantly
  941. * save memory consumption.
  942. *
  943. * <p>If <code>ClassPool.doPruning</code> is true, the automatic pruning
  944. * is on by default. Otherwise, it is off.
  945. *
  946. * @param stop disallow pruning if true. Otherwise, allow.
  947. * @return the previous status of pruning. true if pruning is already stopped.
  948. *
  949. * @see #detach()
  950. * @see #prune()
  951. * @see ClassPool#doPruning
  952. */
  953. public boolean stopPruning(boolean stop) { return true; }
  954. /**
  955. * Discards unnecessary attributes, in particuar,
  956. * <code>CodeAttribute</code>s (method bodies) of the class,
  957. * to minimize the memory footprint.
  958. * After calling this method, the class is read only.
  959. * It cannot be modified any more.
  960. * Furthermore, <code>toBytecode()</code>,
  961. * <code>writeFile()</code>, <code>toClass()</code>,
  962. * or <code>instrument()</code> cannot be called.
  963. * However, the method names and signatures in the class etc.
  964. * are still accessible.
  965. *
  966. * <p><code>toBytecode()</code>, <code>writeFile()</code>, and
  967. * <code>toClass()</code> internally call this method.
  968. *
  969. * @see #toBytecode()
  970. * @see #toClass()
  971. * @see #writeFile()
  972. * @see #instrument(CodeConverter)
  973. * @see #instrument(ExprEditor)
  974. *
  975. * @see #stopPruning(boolean)
  976. */
  977. public void prune() {}
  978. /* Called by get() in ClassPool.
  979. * CtClassType overrides this method.
  980. */
  981. void incGetCounter() {}
  982. /**
  983. * Converts this class to a class file.
  984. * Once this method is called, further modifications are not
  985. * possible any more.
  986. *
  987. * @return the contents of the class file.
  988. */
  989. public byte[] toBytecode() throws IOException, CannotCompileException {
  990. ByteArrayOutputStream barray = new ByteArrayOutputStream();
  991. DataOutputStream out = new DataOutputStream(barray);
  992. try {
  993. toBytecode(out);
  994. }
  995. finally {
  996. out.close();
  997. }
  998. return barray.toByteArray();
  999. }
  1000. /**
  1001. * Writes a class file represented by this <code>CtClass</code>
  1002. * object in the current directory.
  1003. * Once this method is called, further modifications are not
  1004. * possible any more.
  1005. */
  1006. public void writeFile()
  1007. throws NotFoundException, IOException, CannotCompileException
  1008. {
  1009. writeFile(".");
  1010. }
  1011. /**
  1012. * Writes a class file represented by this <code>CtClass</code>
  1013. * object on a local disk.
  1014. * Once this method is called, further modifications are not
  1015. * possible any more.
  1016. *
  1017. * @param directoryName it must end without a directory separator.
  1018. */
  1019. public void writeFile(String directoryName)
  1020. throws NotFoundException, CannotCompileException, IOException
  1021. {
  1022. String classname = getName();
  1023. String filename = directoryName + File.separatorChar
  1024. + classname.replace('.', File.separatorChar) + ".class";
  1025. int pos = filename.lastIndexOf(File.separatorChar);
  1026. if (pos > 0) {
  1027. String dir = filename.substring(0, pos);
  1028. if (!dir.equals("."))
  1029. new File(dir).mkdirs();
  1030. }
  1031. DataOutputStream out
  1032. = new DataOutputStream(new BufferedOutputStream(
  1033. new DelayedFileOutputStream(filename)));
  1034. try {
  1035. toBytecode(out);
  1036. }
  1037. finally {
  1038. out.close();
  1039. }
  1040. }
  1041. /**
  1042. * Writes a class file as <code>writeFile()</code> does although this
  1043. * method does not prune or freeze the class after writing the class
  1044. * file. Note that, once <code>writeFile()</code> or <code>toBytecode()</code>
  1045. * is called, it cannot be called again since the class is pruned and frozen.
  1046. * This method would be useful for debugging.
  1047. */
  1048. public void debugWriteFile() {
  1049. try {
  1050. boolean p = stopPruning(true);
  1051. writeFile();
  1052. defrost();
  1053. stopPruning(p);
  1054. }
  1055. catch (Exception e) {
  1056. throw new RuntimeException(e);
  1057. }
  1058. }
  1059. static class DelayedFileOutputStream extends OutputStream {
  1060. private FileOutputStream file;
  1061. private String filename;
  1062. DelayedFileOutputStream(String name) {
  1063. file = null;
  1064. filename = name;
  1065. }
  1066. private void init() throws IOException {
  1067. if (file == null)
  1068. file = new FileOutputStream(filename);
  1069. }
  1070. public void write(int b) throws IOException {
  1071. init();
  1072. file.write(b);
  1073. }
  1074. public void write(byte[] b) throws IOException {
  1075. init();
  1076. file.write(b);
  1077. }
  1078. public void write(byte[] b, int off, int len) throws IOException {
  1079. init();
  1080. file.write(b, off, len);
  1081. }
  1082. public void flush() throws IOException {
  1083. init();
  1084. file.flush();
  1085. }
  1086. public void close() throws IOException {
  1087. init();
  1088. file.close();
  1089. }
  1090. }
  1091. /**
  1092. * Converts this class to a class file.
  1093. * Once this method is called, further modifications are not
  1094. * possible any more.
  1095. *
  1096. * <p>This method dose not close the output stream in the end.
  1097. *
  1098. * @param out the output stream that a class file is written to.
  1099. */
  1100. public void toBytecode(DataOutputStream out)
  1101. throws CannotCompileException, IOException
  1102. {
  1103. throw new CannotCompileException("not a class");
  1104. }
  1105. /**
  1106. * Makes a unique member name. This method guarantees that
  1107. * the returned name is not used as a prefix of any methods
  1108. * or fields visible in this class.
  1109. * If the returned name is XYZ, then any method or field names
  1110. * in this class do not start with XYZ.
  1111. *
  1112. * @param prefix the prefix of the member name.
  1113. */
  1114. public String makeUniqueName(String prefix) {
  1115. throw new RuntimeException("not available in " + getName());
  1116. }
  1117. }