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

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