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

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