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

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