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

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