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.

tutorial.html 41KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103
  1. <html>
  2. <head>
  3. <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  4. <title>Javassist Tutorial</title>
  5. <link rel="stylesheet" type="text/css" href="brown.css">
  6. </head>
  7. <body>
  8. <b>
  9. <font size="+3">
  10. Getting Started with Javassist
  11. </font>
  12. <p><font size="+2">
  13. Shigeru Chiba
  14. </font>
  15. </b>
  16. <p><div align="right"><a href="tutorial2.html">Next page</a></div>
  17. <ul>1. <a href="#read">Reading and writing bytecode</a>
  18. <br>2. <a href="#pool">ClassPool</a>
  19. <br>3. <a href="#load">Class loader</a>
  20. <br>4. <a href="tutorial2.html#intro">Introspection and customization</a>
  21. <br>5. <a href="tutorial3.html#intro">Bytecode level API</a>
  22. <br>6. <a href="tutorial3.html#generics">Generics</a>
  23. <br>7. <a href="tutorial3.html#varargs">Varargs</a>
  24. <br>8. <a href="tutorial3.html#j2me">J2ME</a>
  25. </ul>
  26. <p><br>
  27. <a name="read">
  28. <h2>1. Reading and writing bytecode</h2>
  29. <p>Javassist is a class library for dealing with Java bytecode.
  30. Java bytecode is stored in a binary file called a class file.
  31. Each class file contains one Java class or interface.
  32. <p>The class <code>Javassist.CtClass</code> is an absatract
  33. representation of a class file. A <code>CtClass</code> (compile-time
  34. class) object is a handle for dealing with a class file. The
  35. following program is a very simple example:
  36. <ul><pre>
  37. ClassPool pool = ClassPool.getDefault();
  38. CtClass cc = pool.get("test.Rectangle");
  39. cc.setSuperclass(pool.get("test.Point"));
  40. cc.writeFile();
  41. </pre></ul>
  42. <p>This program first obtains a <code>ClassPool</code> object, which
  43. controls bytecode modification with Javassist. The
  44. <code>ClassPool</code> object is a container of <code>CtClass</code>
  45. object representing a class file. It reads a class file on demand for
  46. constructing a <code>CtClass</code> object and records the
  47. constructed object for responding later accesses.
  48. To modify the definition of a class, the users must first obtain
  49. from a <code>ClassPool</code> object
  50. a reference to a <code>CtClass</code> object representing that class.
  51. <code>get()</code> in <code>ClassPool</code> is used for this purpose.
  52. In the case of the program shown above, the
  53. <code>CtClass</code> object representing a class
  54. <code>test.Rectangle</code> is obtained from the
  55. <code>ClassPool</code> object and it is assigned to a variable
  56. <code>cc</code>.
  57. The <code>ClassPool</code> object returned by <code>getDfault()</code>
  58. searches the default system search path.
  59. <p>From the implementation viewpoint, <code>ClassPool</code> is a hash
  60. table of <code>CtClass</code> objects, which uses the class names as
  61. keys. <code>get()</code> in <code>ClassPool</code> searches this hash
  62. table to find a <code>CtClass</code> object associated with the
  63. specified key. If such a <code>CtClass</code> object is not found,
  64. <code>get()</code> reads a class file to construct a new
  65. <code>CtClass</code> object, which is recorded in the hash table and
  66. then returned as the resulting value of <code>get()</code>.
  67. <p>The <code>CtClass</code> object obtained from a <code>ClassPool</code>
  68. object can be modified
  69. (<a href="tutorial2.html#intro">details of how to modify
  70. a <code>CtClass</code></a> will be presented later).
  71. In the example above, it is modified so that the superclass of
  72. <code>test.Rectangle</code> is changed into a class
  73. <code>test.Point</code>. This change is reflected on the original
  74. class file when <code>writeFile()</code> in <code>CtClass()</code> is
  75. finally called.
  76. <p><code>writeFile()</code> translates the <code>CtClass</code> object
  77. into a class file and writes it on a local disk.
  78. Javassist also provides a method for directly obtaining the
  79. modified bytecode. To obtain the bytecode, call <code>toBytecode()</code>:
  80. <ul><pre>
  81. byte[] b = cc.toBytecode();
  82. </pre></ul>
  83. <p>You can directly load the <code>CtClass</code> as well:
  84. <ul><pre>
  85. Class clazz = cc.toClass();
  86. </pre></ul>
  87. <p><code>toClass()</code> requests the context class loader for the current
  88. thread to load the class file represented by the <code>CtClass</code>. It
  89. returns a <code>java.lang.Class</code> object representing the loaded class.
  90. For more details, please see <a href="#toclass">this section below</a>.
  91. <a name="def">
  92. <h4>Defining a new class</h4>
  93. <p>To define a new class from scratch, <code>makeClass()</code>
  94. must be called on a <code>ClassPool</code>.
  95. <ul><pre>
  96. ClassPool pool = ClassPool.getDefault();
  97. CtClass cc = pool.makeClass("Point");
  98. </pre></ul>
  99. <p>This program defines a class <code>Point</code>
  100. including no members.
  101. Member methods of <code>Point</code> can be created with
  102. factory methods declared in <code>CtNewMethod</code> and
  103. appended to <code>Point</code> with <code>addMethod()</code>
  104. in <code>CtClass</code>.
  105. <p><code>makeClass()</code> cannot create a new interface;
  106. <code>makeInterface()</code> in <code>ClassPool</code> can do.
  107. Member methods in an interface can be created with
  108. <code>abstractMethod()</code> in <code>CtNewMethod</code>.
  109. Note that an interface method is an abstract method.
  110. <a name="frozenclasses">
  111. <h4>Frozen classes</h4></a>
  112. <p>If a <code>CtClass</code> object is converted into a class file by
  113. <code>writeFile()</code>, <code>toClass()</code>, or
  114. <code>toBytecode()</code>, Javassist freezes that <code>CtClass</code>
  115. object. Further modifications of that <code>CtClass</code> object are
  116. not permitted. This is for warning the developers when they attempt
  117. to modify a class file that has been already loaded since the JVM does
  118. not allow reloading a class.
  119. <p>A frozen <code>CtClass</code> can be defrost so that
  120. modifications of the class definition will be permitted. For example,
  121. <ul><pre>
  122. CtClasss cc = ...;
  123. :
  124. cc.writeFile();
  125. cc.defrost();
  126. cc.setSuperclass(...); // OK since the class is not frozen.
  127. </pre></ul>
  128. <p>After <code>defrost()</code> is called, the <code>CtClass</code>
  129. object can be modified again.
  130. <p>If <code>ClassPool.doPruning</code> is set to <code>true</code>,
  131. then Javassist prunes the data structure contained
  132. in a <code>CtClass</code> object
  133. when Javassist freezes that object.
  134. To reduce memory
  135. consumption, pruning discards unnecessary attributes
  136. (<code>attribute_info</code> structures) in that object.
  137. For example, <code>Code_attribute</code> structures (method bodies)
  138. are discarded.
  139. Thus, after a
  140. <code>CtClass</code> object is pruned, the bytecode of a method is not
  141. accessible except method names, signatures, and annotations.
  142. The pruned <code>CtClass</code> object cannot be defrost again.
  143. The default value of <code>ClassPool.doPruning</code> is <code>false</code>.
  144. <p>To disallow pruning a particular <code>CtClass</code>,
  145. <code>stopPruning()</code> must be called on that object in advance:
  146. <ul><pre>
  147. CtClasss cc = ...;
  148. cc.stopPruning(true);
  149. :
  150. cc.writeFile(); // convert to a class file.
  151. // cc is not pruned.
  152. </pre></ul>
  153. <p>The <code>CtClass</code> object <code>cc</code> is not pruned.
  154. Thus it can be defrost after <code>writeFile()</code> is called.
  155. <ul><b>Note:</b>
  156. While debugging, you might want to temporarily stop pruning and freezing
  157. and write a modified class file to a disk drive.
  158. <code>debugWriteFile()</code> is a convenient method
  159. for that purpose. It stops pruning, writes a class file, defrosts it,
  160. and turns pruning on again (if it was initially on).
  161. </ul>
  162. <h4>Class search path</h4>
  163. <p>The default <code>ClassPool</code> returned
  164. by a static method <code>ClassPool.getDefault()</code>
  165. searches the same path that the underlying JVM (Java virtual machine) has.
  166. <em>If a program is running on a web application server such as JBoss and Tomcat,
  167. the <code>ClassPool</code> object may not be able to find user classes</em>
  168. since such a web application server uses multiple class loaders as well as
  169. the system class loader. In that case, an additional class path must be
  170. registered to the <code>ClassPool</code>. Suppose that <code>pool</code>
  171. refers to a <code>ClassPool</code> object:
  172. <ul><pre>
  173. pool.insertClassPath(new ClassClassPath(this.getClass()));
  174. </pre></ul>
  175. <p>
  176. This statement registers the class path that was used for loading
  177. the class of the object that <code>this</code> refers to.
  178. You can use any <code>Class</code> object as an argument instead of
  179. <code>this.getClass()</code>. The class path used for loading the
  180. class represented by that <code>Class</code> object is registered.
  181. <p>
  182. You can register a directory name as the class search path.
  183. For example, the following code adds a directory
  184. <code>/usr/local/javalib</code>
  185. to the search path:
  186. <ul><pre>
  187. ClassPool pool = ClassPool.getDefault();
  188. pool.insertClassPath("/usr/local/javalib");
  189. </pre></ul>
  190. <p>The search path that the users can add is not only a directory but also
  191. a URL:
  192. <ul><pre>
  193. ClassPool pool = ClassPool.getDefault();
  194. ClassPath cp = new URLClassPath("www.javassist.org", 80, "/java/", "org.javassist.");
  195. pool.insertClassPath(cp);
  196. </pre></ul>
  197. <p>This program adds "http://www.javassist.org:80/java/" to the class search
  198. path. This URL is used only for searching classes belonging to a
  199. package <code>org.javassist</code>. For example, to load a class
  200. <code>org.javassist.test.Main</code>, its class file will be obtained from:
  201. <ul><pre>http://www.javassist.org:80/java/org/javassist/test/Main.class
  202. </pre></ul>
  203. <p>Furthermore, you can directly give a byte array
  204. to a <code>ClassPool</code> object
  205. and construct a <code>CtClass</code> object from that array. To do this,
  206. use <code>ByteArrayClassPath</code>. For example,
  207. <ul><pre>
  208. ClassPool cp = ClassPool.getDefault();
  209. byte[] b = <em>a byte array</em>;
  210. String name = <em>class name</em>;
  211. cp.insertClassPath(new ByteArrayClassPath(name, b));
  212. CtClass cc = cp.get(name);
  213. </pre></ul>
  214. <p>The obtained <code>CtClass</code> object represents
  215. a class defined by the class file specified by <code>b</code>.
  216. The <code>ClassPool</code> reads a class file from the given
  217. <code>ByteArrayClassPath</code> if <code>get()</code> is called
  218. and the class name given to <code>get()</code> is equal to
  219. one specified by <code>name</code>.
  220. <p>If you do not know the fully-qualified name of the class, then you
  221. can use <code>makeClass()</code> in <code>ClassPool</code>:
  222. <ul><pre>
  223. ClassPool cp = ClassPool.getDefault();
  224. InputStream ins = <em>an input stream for reading a class file</em>;
  225. CtClass cc = cp.makeClass(ins);
  226. </pre></ul>
  227. <p><code>makeClass()</code> returns the <code>CtClass</code> object
  228. constructed from the given input stream. You can use
  229. <code>makeClass()</code> for eagerly feeding class files to
  230. the <code>ClassPool</code> object. This might improve performance
  231. if the search path includes a large jar file. Since
  232. a <code>ClassPool</code> object reads a class file on demand,
  233. it might repeatedly search the whole jar file for every class file.
  234. <code>makeClass()</code> can be used for optimizing this search.
  235. The <code>CtClass</code> constructed by <code>makeClass()</code>
  236. is kept in the <code>ClassPool</code> object and the class file is never
  237. read again.
  238. <p>The users can extend the class search path. They can define a new
  239. class implementing <code>ClassPath</code> interface and give an
  240. instance of that class to <code>insertClassPath()</code> in
  241. <code>ClassPool</code>. This allows a non-standard resource to be
  242. included in the search path.
  243. <p><br>
  244. <a name="pool">
  245. <h2>2. ClassPool</h2>
  246. <p>
  247. A <code>ClassPool</code> object is a container of <code>CtClass</code>
  248. objects. Once a <code>CtClass</code> object is created, it is
  249. recorded in a <code>ClassPool</code> for ever. This is because a
  250. compiler may need to access the <code>CtClass</code> object later when
  251. it compiles source code that refers to the class represented by that
  252. <code>CtClass</code>.
  253. <p>
  254. For example, suppose that a new method <code>getter()</code> is added
  255. to a <code>CtClass</code> object representing <code>Point</code>
  256. class. Later, the program attempts to compile source code including a
  257. method call to <code>getter()</code> in <code>Point</code> and use the
  258. compiled code as the body of a method, which will be added to another
  259. class <code>Line</code>. If the <code>CtClass</code> object representing
  260. <code>Point</code> is lost, the compiler cannot compile the method call
  261. to <code>getter()</code>. Note that the original class definition does
  262. not include <code>getter()</code>. Therefore, to correctly compile
  263. such a method call, the <code>ClassPool</code>
  264. must contain all the instances of <code>CtClass</code> all the time of
  265. program execution.
  266. <a name="avoidmemory">
  267. <h4>Avoid out of memory</h4>
  268. </a>
  269. <p>
  270. This specification of <code>ClassPool</code> may cause huge memory
  271. consumption if the number of <code>CtClass</code> objects becomes
  272. amazingly large (this rarely happens since Javassist tries to reduce
  273. memory consumption in <a href="#frozenclasses">various ways</a>).
  274. To avoid this problem, you
  275. can explicitly remove an unnecessary <code>CtClass</code> object from
  276. the <code>ClassPool</code>. If you call <code>detach()</code> on a
  277. <code>CtClass</code> object, then that <code>CtClass</code> object is
  278. removed from the <code>ClassPool</code>. For example,
  279. <ul><pre>
  280. CtClass cc = ... ;
  281. cc.writeFile();
  282. cc.detach();
  283. </pre></ul>
  284. <p>You must not call any method on that
  285. <code>CtClass</code> object after <code>detach()</code> is called.
  286. However, you can call <code>get()</code> on <code>ClassPool</code>
  287. to make a new instance of <code>CtClass</code> representing
  288. the same class. If you call <code>get()</code>, the <code>ClassPool</code>
  289. reads a class file again and newly creates a <code>CtClass</code>
  290. object, which is returned by <code>get()</code>.
  291. <p>
  292. Another idea is to occasionally replace a <code>ClassPool</code> with
  293. a new one and discard the old one. If an old <code>ClassPool</code>
  294. is garbage collected, the <code>CtClass</code> objects included in
  295. that <code>ClassPool</code> are also garbage collected.
  296. To create a new instance of <code>ClassPool</code>, execute the following
  297. code snippet:
  298. <ul><pre>
  299. ClassPool cp = new ClassPool(true);
  300. // if needed, append an extra search path by appendClassPath()
  301. </pre></ul>
  302. <p>This creates a <code>ClassPool</code> object that behaves as the
  303. default <code>ClassPool</code> returned by
  304. <code>ClassPool.getDefault()</code> does.
  305. Note that <code>ClassPool.getDefault()</code> is a singleton factory method
  306. provided for convenience. It creates a <code>ClassPool</code> object in
  307. the same way shown above although it keeps a single instance of
  308. <code>ClassPool</code> and reuses it.
  309. A <code>ClassPool</code> object returned by <code>getDefault()</code>
  310. does not have a special role. <code>getDefault()</code> is a convenience
  311. method.
  312. <p>Note that <code>new ClassPool(true)</code> is a convenient constructor,
  313. which constructs a <code>ClassPool</code> object and appends the system
  314. search path to it. Calling that constructor is
  315. equivalent to the following code:
  316. <ul><pre>
  317. ClassPool cp = new ClassPool();
  318. cp.appendSystemPath(); // or append another path by appendClassPath()
  319. </pre></ul>
  320. <h4>Cascaded ClassPools</h4>
  321. <p>
  322. <em>If a program is running on a web application server,</em>
  323. creating multiple instances of <code>ClassPool</code> might be necessary;
  324. an instance of <code>ClassPool</code> should be created
  325. for each class loader (i.e. container).
  326. The program should create a <code>ClassPool</code> object by not calling
  327. <code>getDefault()</code> but a constructor of <code>ClassPool</code>.
  328. <p>
  329. Multiple <code>ClassPool</code> objects can be cascaded like
  330. <code>java.lang.ClassLoader</code>. For example,
  331. <ul><pre>
  332. ClassPool parent = ClassPool.getDefault();
  333. ClassPool child = new ClassPool(parent);
  334. child.insertClassPath("./classes");
  335. </pre></ul>
  336. <p>
  337. If <code>child.get()</code> is called, the child <code>ClassPool</code>
  338. first delegates to the parent <code>ClassPool</code>. If the parent
  339. <code>ClassPool</code> fails to find a class file, then the child
  340. <code>ClassPool</code> attempts to find a class file
  341. under the <code>./classes</code> directory.
  342. <p>
  343. If <code>child.childFirstLookup</code> is true, the child
  344. <code>ClassPool</code> attempts to find a class file before delegating
  345. to the parent <code>ClassPool</code>. For example,
  346. <ul><pre>
  347. ClassPool parent = ClassPool.getDefault();
  348. ClassPool child = new ClassPool(parent);
  349. child.appendSystemPath(); // the same class path as the default one.
  350. child.childFirstLookup = true; // changes the behavior of the child.
  351. </pre></ul>
  352. <h4>Changing a class name for defining a new class</h4>
  353. <p>A new class can be defined as a copy of an existing class.
  354. The program below does that:
  355. <ul><pre>
  356. ClassPool pool = ClassPool.getDefault();
  357. CtClass cc = pool.get("Point");
  358. cc.setName("Pair");
  359. </pre></ul>
  360. <p>This program first obtains the <code>CtClass</code> object for
  361. class <code>Point</code>. Then it calls <code>setName()</code> to
  362. give a new name <code>Pair</code> to that <code>CtClass</code> object.
  363. After this call, all occurrences of the class name in the class
  364. definition represented by that <code>CtClass</code> object are changed
  365. from <code>Point</code> to <code>Pair</code>. The other part of the
  366. class definition does not change.
  367. <p>Note that <code>setName()</code> in <code>CtClass</code> changes a
  368. record in the <code>ClassPool</code> object. From the implementation
  369. viewpoint, a <code>ClassPool</code> object is a hash table of
  370. <code>CtClass</code> objects. <code>setName()</code> changes
  371. the key associated to the <code>CtClass</code> object in the hash
  372. table. The key is changed from the original class name to the new
  373. class name.
  374. <p>Therefore, if <code>get("Point")</code> is later called on the
  375. <code>ClassPool</code> object again, then it never returns the
  376. <code>CtClass</code> object that the variable <code>cc</code> refers to.
  377. The <code>ClassPool</code> object reads
  378. a class file
  379. <code>Point.class</code> again and it constructs a new <code>CtClass</code>
  380. object for class <code>Point</code>.
  381. This is because the <code>CtClass</code> object associated with the name
  382. <code>Point</code> does not exist any more.
  383. See the followings:
  384. <ul><pre>
  385. ClassPool pool = ClassPool.getDefault();
  386. CtClass cc = pool.get("Point");
  387. CtClass cc1 = pool.get("Point"); // cc1 is identical to cc.
  388. cc.setName("Pair");
  389. CtClass cc2 = pool.get("Pair"); // cc2 is identical to cc.
  390. CtClass cc3 = pool.get("Point"); // cc3 is not identical to cc.
  391. </pre></ul>
  392. <p><code>cc1</code> and <code>cc2</code> refer to the same instance of
  393. <code>CtClass</code> that <code>cc</code> does whereas
  394. <code>cc3</code> does not. Note that, after
  395. <code>cc.setName("Pair")</code> is executed, the <code>CtClass</code>
  396. object that <code>cc</code> and <code>cc1</code> refer to represents
  397. the <code>Pair</code> class.
  398. <p>The <code>ClassPool</code> object is used to maintain one-to-one
  399. mapping between classes and <code>CtClass</code> objects. Javassist
  400. never allows two distinct <code>CtClass</code> objects to represent
  401. the same class unless two independent <code>ClassPool</code> are created.
  402. This is a significant feature for consistent program
  403. transformation.
  404. <p>To create another copy of the default instance of
  405. <code>ClassPool</code>, which is returned by
  406. <code>ClassPool.getDefault()</code>, execute the following code
  407. snippet (this code was already <a href="#avoidmemory">shown above</a>):
  408. <ul><pre>
  409. ClassPool cp = new ClassPool(true);
  410. </pre></ul>
  411. <p>If you have two <code>ClassPool</code> objects, then you can
  412. obtain, from each <code>ClassPool</code>, a distinct
  413. <code>CtClass</code> object representing the same class file. You can
  414. differently modify these <code>CtClass</code> objects to generate
  415. different versions of the class.
  416. <h4>Renaming a frozen class for defining a new class</h4>
  417. <p>Once a <code>CtClass</code> object is converted into a class file
  418. by <code>writeFile()</code> or <code>toBytecode()</code>, Javassist
  419. rejects further modifications of that <code>CtClass</code> object.
  420. Hence, after the <code>CtClass</code> object representing <code>Point</code>
  421. class is converted into a class file, you cannot define <code>Pair</code>
  422. class as a copy of <code>Point</code> since executing <code>setName()</code>
  423. on <code>Point</code> is rejected.
  424. The following code snippet is wrong:
  425. <ul><pre>
  426. ClassPool pool = ClassPool.getDefault();
  427. CtClass cc = pool.get("Point");
  428. cc.writeFile();
  429. cc.setName("Pair"); // wrong since writeFile() has been called.
  430. </pre></ul>
  431. <p>To avoid this restriction, you should call <code>getAndRename()</code>
  432. in <code>ClassPool</code>. For example,
  433. <ul><pre>
  434. ClassPool pool = ClassPool.getDefault();
  435. CtClass cc = pool.get("Point");
  436. cc.writeFile();
  437. CtClass cc2 = pool.getAndRename("Point", "Pair");
  438. </pre></ul>
  439. <p>If <code>getAndRename()</code> is called, the <code>ClassPool</code>
  440. first reads <code>Point.class</code> for creating a new <code>CtClass</code>
  441. object representing <code>Point</code> class. However, it renames that
  442. <code>CtClass</code> object from <code>Point</code> to <code>Pair</code> before
  443. it records that <code>CtClass</code> object in a hash table.
  444. Thus <code>getAndRename()</code>
  445. can be executed after <code>writeFile()</code> or <code>toBytecode()</code>
  446. is called on the the <code>CtClass</code> object representing <code>Point</code>
  447. class.
  448. <p><br>
  449. <a name="load">
  450. <h2>3. Class loader</h2>
  451. <p>If what classes must be modified is known in advance,
  452. the easiest way for modifying the classes is as follows:
  453. <ul><li>1. Get a <code>CtClass</code> object by calling
  454. <code>ClassPool.get()</code>,
  455. <li>2. Modify it, and
  456. <li>3. Call <code>writeFile()</code> or <code>toBytecode()</code>
  457. on that <code>CtClass</code> object to obtain a modified class file.
  458. </ul>
  459. <p>If whether a class is modified or not is determined at load time,
  460. the users must make Javassist collaborate with a class loader.
  461. Javassist can be used with a class loader so that bytecode can be
  462. modified at load time. The users of Javassist can define their own
  463. version of class loader but they can also use a class loader provided
  464. by Javassist.
  465. <p><br>
  466. <a name="toclass">
  467. <h3>3.1 The <code>toClass</code> method in <code>CtClass</code></h3>
  468. </a>
  469. <p>The <code>CtClass</code> provides a convenience method
  470. <code>toClass()</code>, which requests the context class loader for
  471. the current thread to load the class represented by the <code>CtClass</code>
  472. object. To call this method, the caller must have appropriate permission;
  473. otherwise, a <code>SecurityException</code> may be thrown.
  474. <p>The following program shows how to use <code>toClass()</code>:
  475. <ul><pre>
  476. public class Hello {
  477. public void say() {
  478. System.out.println("Hello");
  479. }
  480. }
  481. public class Test {
  482. public static void main(String[] args) throws Exception {
  483. ClassPool cp = ClassPool.getDefault();
  484. CtClass cc = cp.get("Hello");
  485. CtMethod m = cc.getDeclaredMethod("say");
  486. m.insertBefore("{ System.out.println(\"Hello.say():\"); }");
  487. Class c = cc.toClass();
  488. Hello h = (Hello)c.newInstance();
  489. h.say();
  490. }
  491. }
  492. </pre></ul>
  493. <p><code>Test.main()</code> inserts a call to <code>println()</code>
  494. in the method body of <code>say()</code> in <code>Hello</code>. Then
  495. it constructs an instance of the modified <code>Hello</code> class
  496. and calls <code>say()</code> on that instance.
  497. <p>Note that the program above depends on the fact that the
  498. <code>Hello</code> class is never loaded before <code>toClass()</code>
  499. is invoked. If not, the JVM would load the original
  500. <code>Hello</code> class before <code>toClass()</code> requests to
  501. load the modified <code>Hello</code> class. Hence loading the
  502. modified <code>Hello</code> class would be failed
  503. (<code>LinkageError</code> is thrown). For example, if
  504. <code>main()</code> in <code>Test</code> is something like this:
  505. <ul><pre>
  506. public static void main(String[] args) throws Exception {
  507. Hello orig = new Hello();
  508. ClassPool cp = ClassPool.getDefault();
  509. CtClass cc = cp.get("Hello");
  510. :
  511. }
  512. </pre></ul>
  513. <p>then the original <code>Hello</code> class is loaded at the first
  514. line of <code>main</code> and the call to <code>toClass()</code>
  515. throws an exception since the class loader cannot load two different
  516. versions of the <code>Hello</code> class at the same time.
  517. <p><em>If the program is running on some application server such as
  518. JBoss and Tomcat,</em> the context class loader used by
  519. <code>toClass()</code> might be inappropriate. In this case, you
  520. would see an unexpected <code>ClassCastException</code>. To avoid
  521. this exception, you must explicitly give an appropriate class loader
  522. to <code>toClass()</code>. For example, if <code>bean</code> is your
  523. session bean object, then the following code:
  524. <ul><pre>CtClass cc = ...;
  525. Class c = cc.toClass(bean.getClass().getClassLoader());
  526. </pre></ul>
  527. <p>would work. You should give <code>toClass()</code> the class loader
  528. that has loaded your program (in the above example, the class of
  529. the <code>bean</code> object).
  530. <p><code>toClass()</code> is provided for convenience. If you need
  531. more complex functionality, you should write your own class loader.
  532. <p><br>
  533. <h3>3.2 Class loading in Java</h3>
  534. <p>In Java, multiple class loaders can coexist and
  535. each class loader creates its own name space.
  536. Different class loaders can load different class files with the
  537. same class name. The loaded two classes are regarded as different
  538. ones. This feature enables us to run multiple application programs
  539. on a single JVM even if these programs include different classes
  540. with the same name.
  541. <ul>
  542. <b>Note:</b> The JVM does not allow dynamically reloading a class.
  543. Once a class loader loads a class, it cannot reload a modified
  544. version of that class during runtime. Thus, you cannot alter
  545. the definition of a class after the JVM loads it.
  546. However, the JPDA (Java Platform Debugger Architecture) provides
  547. limited ability for reloading a class.
  548. See <a href="#hotswap">Section 3.6</a>.
  549. </ul>
  550. <p>If the same class file is loaded by two distinct class loaders,
  551. the JVM makes two distinct classes with the same name and definition.
  552. The two classes are regarded as different ones.
  553. Since the two classes are not identical, an instance of one class is
  554. not assignable to a variable of the other class. The cast operation
  555. between the two classes fails
  556. and throws a <em><code>ClassCastException</code></em>.
  557. <p>For example, the following code snippet throws an exception:
  558. <ul><pre>
  559. MyClassLoader myLoader = new MyClassLoader();
  560. Class clazz = myLoader.loadClass("Box");
  561. Object obj = clazz.newInstance();
  562. Box b = (Box)obj; // this always throws ClassCastException.
  563. </pre></ul>
  564. <p>
  565. The <code>Box</code> class is loaded by two class loaders.
  566. Suppose that a class loader CL loads a class including this code snippet.
  567. Since this code snippet refers to <code>MyClassLoader</code>,
  568. <code>Class</code>, <code>Object</code>, and <code>Box</code>,
  569. CL also loads these classes (unless it delegates to another class loader).
  570. Hence the type of the variable <code>b</code> is the <code>Box</code>
  571. class loaded by CL.
  572. On the other hand, <code>myLoader</code> also loads the <code>Box</code>
  573. class. The object <code>obj</code> is an instance of
  574. the <code>Box</code> class loaded by <code>myLoader</code>.
  575. Therefore, the last statement always throws a
  576. <code>ClassCastException</code> since the class of <code>obj</code> is
  577. a different verison of the <code>Box</code> class from one used as the
  578. type of the variable <code>b</code>.
  579. <p>Multiple class loaders form a tree structure.
  580. Each class loader except the bootstrap loader has a
  581. parent class loader, which has normally loaded the class of that child
  582. class loader. Since the request to load a class can be delegated along this
  583. hierarchy of class loaders, a class may be loaded by a class loader that
  584. you do not request the class loading.
  585. Therefore, the class loader that has been requested to load a class C
  586. may be different from the loader that actually loads the class C.
  587. For distinction, we call the former loader <em>the initiator of C</em>
  588. and we call the latter loader <em>the real loader of C</em>.
  589. <p>
  590. Furthermore, if a class loader CL requested to load a class C
  591. (the initiator of C) delegates
  592. to the parent class loader PL, then the class loader CL is never requested
  593. to load any classes referred to in the definition of the class C.
  594. CL is not the initiator of those classes.
  595. Instead, the parent class loader PL becomes their initiators
  596. and it is requested to load them.
  597. <em>The classes that the definition of a class C referes to are loaded by
  598. the real loader of C.</em>
  599. <p>To understand this behavior, let's consider the following example.
  600. <ul><pre>
  601. public class Point { // loaded by PL
  602. private int x, y;
  603. public int getX() { return x; }
  604. :
  605. }
  606. public class Box { // the initiator is L but the real loader is PL
  607. private Point upperLeft, size;
  608. public int getBaseX() { return upperLeft.x; }
  609. :
  610. }
  611. public class Window { // loaded by a class loader L
  612. private Box box;
  613. public int getBaseX() { return box.getBaseX(); }
  614. }</pre></ul>
  615. <p>Suppose that a class <code>Window</code> is loaded by a class loader L.
  616. Both the initiator and the real loader of <code>Window</code> are L.
  617. Since the definition of <code>Window</code> refers to <code>Box</code>,
  618. the JVM will request L to load <code>Box</code>.
  619. Here, suppose that L delegates this task to the parent class loader PL.
  620. The initiator of <code>Box</code> is L but the real loader is PL.
  621. In this case, the initiator of <code>Point</code> is not L but PL
  622. since it is the same as the real loader of <code>Box</code>.
  623. Thus L is never requested to load <code>Point</code>.
  624. <p>Next, let's consider a slightly modified example.
  625. <ul><pre>
  626. public class Point {
  627. private int x, y;
  628. public int getX() { return x; }
  629. :
  630. }
  631. public class Box { // the initiator is L but the real loader is PL
  632. private Point upperLeft, size;
  633. public Point getSize() { return size; }
  634. :
  635. }
  636. public class Window { // loaded by a class loader L
  637. private Box box;
  638. public boolean widthIs(int w) {
  639. Point p = box.getSize();
  640. return w == p.getX();
  641. }
  642. }</pre></ul>
  643. <p>Now, the definition of <code>Window</code> also refers to
  644. <code>Point</code>. In this case, the class loader L must
  645. also delegate to PL if it is requested to load <code>Point</code>.
  646. <em>You must avoid having two class loaders doubly load the same
  647. class.</em> One of the two loaders must delegate to
  648. the other.
  649. <p>
  650. If L does not delegate to PL when <code>Point</code>
  651. is loaded, <code>widthIs()</code> would throw a ClassCastException.
  652. Since the real loader of <code>Box</code> is PL,
  653. <code>Point</code> referred to in <code>Box</code> is also loaded by PL.
  654. Therefore, the resulting value of <code>getSize()</code>
  655. is an instance of <code>Point</code> loaded by PL
  656. whereas the type of the variable <code>p</code> in <code>widthIs()</code>
  657. is <code>Point</code> loaded by L.
  658. The JVM regards them as distinct types and thus it throws an exception
  659. because of type mismatch.
  660. <p>This behavior is somewhat inconvenient but necessary.
  661. If the following statement:
  662. <ul><pre>
  663. Point p = box.getSize();
  664. </pre></ul>
  665. <p>did not throw an exception,
  666. then the programmer of <code>Window</code> could break the encapsulation
  667. of <code>Point</code> objects.
  668. For example, the field <code>x</code>
  669. is private in <code>Point</code> loaded by PL.
  670. However, the <code>Window</code> class could
  671. directly access the value of <code>x</code>
  672. if L loads <code>Point</code> with the following definition:
  673. <ul><pre>
  674. public class Point {
  675. public int x, y; // not private
  676. public int getX() { return x; }
  677. :
  678. }
  679. </pre></ul>
  680. <p>
  681. For more details of class loaders in Java, the following paper would
  682. be helpful:
  683. <ul>Sheng Liang and Gilad Bracha,
  684. "Dynamic Class Loading in the Java Virtual Machine",
  685. <br><i>ACM OOPSLA'98</i>, pp.36-44, 1998.</ul>
  686. <p><br>
  687. <h3>3.3 Using <code>javassist.Loader</code></h3>
  688. <p>Javassist provides a class loader
  689. <code>javassist.Loader</code>. This class loader uses a
  690. <code>javassist.ClassPool</code> object for reading a class file.
  691. <p>For example, <code>javassist.Loader</code> can be used for loading
  692. a particular class modified with Javassist.
  693. <ul><pre>
  694. import javassist.*;
  695. import test.Rectangle;
  696. public class Main {
  697. public static void main(String[] args) throws Throwable {
  698. ClassPool pool = ClassPool.getDefault();
  699. Loader cl = new Loader(pool);
  700. CtClass ct = pool.get("test.Rectangle");
  701. ct.setSuperclass(pool.get("test.Point"));
  702. Class c = cl.loadClass("test.Rectangle");
  703. Object rect = c.newInstance();
  704. :
  705. }
  706. }
  707. </pre></ul>
  708. <p>This program modifies a class <code>test.Rectangle</code>. The
  709. superclass of <code>test.Rectangle</code> is set to a
  710. <code>test.Point</code> class. Then this program loads the modified
  711. class, and creates a new instance of the
  712. <code>test.Rectangle</code> class.
  713. <p>If the users want to modify a class on demand when it is loaded,
  714. the users can add an event listener to a <code>javassist.Loader</code>.
  715. The added event listener is
  716. notified when the class loader loads a class.
  717. The event-listener class must implement the following interface:
  718. <ul><pre>public interface Translator {
  719. public void start(ClassPool pool)
  720. throws NotFoundException, CannotCompileException;
  721. public void onLoad(ClassPool pool, String classname)
  722. throws NotFoundException, CannotCompileException;
  723. }</pre></ul>
  724. <p>The method <code>start()</code> is called when this event listener
  725. is added to a <code>javassist.Loader</code> object by
  726. <code>addTranslator()</code> in <code>javassist.Loader</code>. The
  727. method <code>onLoad()</code> is called before
  728. <code>javassist.Loader</code> loads a class. <code>onLoad()</code>
  729. can modify the definition of the loaded class.
  730. <p>For example, the following event listener changes all classes
  731. to public classes just before they are loaded.
  732. <ul><pre>public class MyTranslator implements Translator {
  733. void start(ClassPool pool)
  734. throws NotFoundException, CannotCompileException {}
  735. void onLoad(ClassPool pool, String classname)
  736. throws NotFoundException, CannotCompileException
  737. {
  738. CtClass cc = pool.get(classname);
  739. cc.setModifiers(Modifier.PUBLIC);
  740. }
  741. }</pre></ul>
  742. <p>Note that <code>onLoad()</code> does not have to call
  743. <code>toBytecode()</code> or <code>writeFile()</code> since
  744. <code>javassist.Loader</code> calls these methods to obtain a class
  745. file.
  746. <p>To run an application class <code>MyApp</code> with a
  747. <code>MyTranslator</code> object, write a main class as following:
  748. <ul><pre>
  749. import javassist.*;
  750. public class Main2 {
  751. public static void main(String[] args) throws Throwable {
  752. Translator t = new MyTranslator();
  753. ClassPool pool = ClassPool.getDefault();
  754. Loader cl = new Loader();
  755. cl.addTranslator(pool, t);
  756. cl.run("MyApp", args);
  757. }
  758. }
  759. </pre></ul>
  760. <p>To run this program, do:
  761. <ul><pre>
  762. % java Main2 <i>arg1</i> <i>arg2</i>...
  763. </pre></ul>
  764. <p>The class <code>MyApp</code> and the other application classes
  765. are translated by <code>MyTranslator</code>.
  766. <p>Note that <em>application</em> classes like <code>MyApp</code> cannot
  767. access the <em>loader</em> classes such as <code>Main2</code>,
  768. <code>MyTranslator</code>, and <code>ClassPool</code> because they
  769. are loaded by different loaders. The application classes are loaded
  770. by <code>javassist.Loader</code> whereas the loader classes such as
  771. <code>Main2</code> are by the default Java class loader.
  772. <p><code>javassist.Loader</code> searches for classes in a different
  773. order from <code>java.lang.ClassLoader</code>.
  774. <code>ClassLoader</code> first delegates the loading operations to
  775. the parent class loader and then attempts to load the classes
  776. only if the parent class loader cannot find them.
  777. On the other hand,
  778. <code>javassist.Loader</code> attempts
  779. to load the classes before delegating to the parent class loader.
  780. It delegates only if:
  781. <ul><li>the classes are not found by calling <code>get()</code> on
  782. a <code>ClassPool</code> object, or
  783. <p><li>the classes have been specified by using
  784. <code>delegateLoadingOf()</code>
  785. to be loaded by the parent class loader.
  786. </ul>
  787. <p>This search order allows loading modified classes by Javassist.
  788. However, it delegates to the parent class loader if it fails
  789. to find modified classes for some reason. Once a class is loaded by
  790. the parent class loader, the other classes referred to in that class will be
  791. also loaded by the parent class loader and thus they are never modified.
  792. Recall that all the classes referred to in a class C are loaded by the
  793. real loader of C.
  794. <em>If your program fails to load a modified class,</em> you should
  795. make sure whether all the classes using that class have been loaded by
  796. <code>javassist.Loader</code>.
  797. <p><br>
  798. <h3>3.4 Writing a class loader</h3>
  799. <p>A simple class loader using Javassist is as follows:
  800. <ul><pre>import javassist.*;
  801. public class SampleLoader extends ClassLoader {
  802. /* Call MyApp.main().
  803. */
  804. public static void main(String[] args) throws Throwable {
  805. SampleLoader s = new SampleLoader();
  806. Class c = s.loadClass("MyApp");
  807. c.getDeclaredMethod("main", new Class[] { String[].class })
  808. .invoke(null, new Object[] { args });
  809. }
  810. private ClassPool pool;
  811. public SampleLoader() throws NotFoundException {
  812. pool = new ClassPool();
  813. pool.insertClassPath("./class"); // <em>MyApp.class must be there.</em>
  814. }
  815. /* Finds a specified class.
  816. * The bytecode for that class can be modified.
  817. */
  818. protected Class findClass(String name) throws ClassNotFoundException {
  819. try {
  820. CtClass cc = pool.get(name);
  821. // <em>modify the CtClass object here</em>
  822. byte[] b = cc.toBytecode();
  823. return defineClass(name, b, 0, b.length);
  824. } catch (NotFoundException e) {
  825. throw new ClassNotFoundException();
  826. } catch (IOException e) {
  827. throw new ClassNotFoundException();
  828. } catch (CannotCompileException e) {
  829. throw new ClassNotFoundException();
  830. }
  831. }
  832. }</pre></ul>
  833. <p>The class <code>MyApp</code> is an application program.
  834. To execute this program, first put the class file under the
  835. <code>./class</code> directory, which must <em>not</em> be included
  836. in the class search path. Otherwise, <code>MyApp.class</code> would
  837. be loaded by the default system class loader, which is the parent
  838. loader of <code>SampleLoader</code>.
  839. The directory name <code>./class</code> is specified by
  840. <code>insertClassPath()</code> in the constructor.
  841. You can choose a different name instead of <code>./class</code> if you want.
  842. Then do as follows:
  843. <ul><code>% java SampleLoader</code></ul>
  844. <p>The class loader loads the class <code>MyApp</code>
  845. (<code>./class/MyApp.class</code>) and calls
  846. <code>MyApp.main()</code> with the command line parameters.
  847. <p>This is the simplest way of using Javassist. However, if you write
  848. a more complex class loader, you may need detailed knowledge of
  849. Java's class loading mechanism. For example, the program above puts the
  850. <code>MyApp</code> class in a name space separated from the name space
  851. that the class <code>SampleLoader</code> belongs to because the two
  852. classes are loaded by different class loaders.
  853. Hence, the
  854. <code>MyApp</code> class cannot directly access the class
  855. <code>SampleLoader</code>.
  856. <p><br>
  857. <h3>3.5 Modifying a system class</h3>
  858. <p>The system classes like <code>java.lang.String</code> cannot be
  859. loaded by a class loader other than the system class loader.
  860. Therefore, <code>SampleLoader</code> or <code>javassist.Loader</code>
  861. shown above cannot modify the system classes at loading time.
  862. <p>If your application needs to do that, the system classes must be
  863. <em>statically</em> modified. For example, the following program
  864. adds a new field <code>hiddenValue</code> to <code>java.lang.String</code>:
  865. <ul><pre>ClassPool pool = ClassPool.getDefault();
  866. CtClass cc = pool.get("java.lang.String");
  867. CtField f = new CtField(CtClass.intType, "hiddenValue", cc);
  868. f.setModifiers(Modifier.PUBLIC);
  869. cc.addField(f);
  870. cc.writeFile(".");</pre></ul>
  871. <p>This program produces a file <code>"./java/lang/String.class"</code>.
  872. <p>To run your program <code>MyApp</code>
  873. with this modified <code>String</code> class, do as follows:
  874. <ul><pre>
  875. % java -Xbootclasspath/p:. MyApp <i>arg1</i> <i>arg2</i>...
  876. </pre></ul>
  877. <p>Suppose that the definition of <code>MyApp</code> is as follows:
  878. <ul><pre>public class MyApp {
  879. public static void main(String[] args) throws Exception {
  880. System.out.println(String.class.getField("hiddenValue").getName());
  881. }
  882. }</pre></ul>
  883. <p>If the modified <code>String</code> class is correctly loaded,
  884. <code>MyApp</code> prints <code>hiddenValue</code>.
  885. <p><i>Note: Applications that use this technique for the purpose of
  886. overriding a system class in <code>rt.jar</code> should not be
  887. deployed as doing so would contravene the Java 2 Runtime Environment
  888. binary code license.</i>
  889. <p><br>
  890. <a name="hotswap">
  891. <h3>3.6 Reloading a class at runtime</h3></a>
  892. <p>If the JVM is launched with the JPDA (Java Platform Debugger
  893. Architecture) enabled, a class is dynamically reloadable. After the
  894. JVM loads a class, the old version of the class definition can be
  895. unloaded and a new one can be reloaded again. That is, the definition
  896. of that class can be dynamically modified during runtime. However,
  897. the new class definition must be somewhat compatible to the old one.
  898. <em>The JVM does not allow schema changes between the two versions.</em>
  899. They have the same set of methods and fields.
  900. <p>Javassist provides a convenient class for reloading a class at runtime.
  901. For more information, see the API documentation of
  902. <code>javassist.tools.HotSwapper</code>.
  903. <p><br>
  904. <a href="tutorial2.html">Next page</a>
  905. <hr>
  906. Java(TM) is a trademark of Sun Microsystems, Inc.<br>
  907. Copyright (C) 2000-2010 by Shigeru Chiba, All rights reserved.
  908. </body>
  909. </html>