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.

tutorial3.html 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  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. <div align="right">Getting Started with Javassist</div>
  9. <div align="left"><a href="tutorial2.html">Previous page</a></div>
  10. <p>
  11. <a href="#intro">5. Bytecode level API</a>
  12. <ul>
  13. <li><a href="#classfile">Obtaining a <code>ClassFile</code> object</a>
  14. <br><li><a href="#member">Adding and removing a member</a>
  15. <br><li><a href="#traverse">Traversing a method body</a>
  16. <br><li><a href="#bytecode">Producing a bytecode sequence</a>
  17. <br><li><a href="#annotation">Annotations (Meta tags)</a>
  18. </ul>
  19. <p><a href="#generics">6. Generics</a>
  20. <p><a href="#varargs">7. Varargs</a>
  21. <p><a href="#j2me">8. J2ME</a>
  22. <p><a href="#boxing">9. Boxing/Unboxing
  23. <p><a href="#debug">10. Debug</a>
  24. <p><br>
  25. <a name="intro">
  26. <h2>5. Bytecode level API</h2>
  27. <p>
  28. Javassist also provides lower-level API for directly editing
  29. a class file. To use this level of API, you need detailed
  30. knowledge of the Java bytecode and the class file format
  31. while this level of API allows you any kind of modification
  32. of class files.
  33. <p>
  34. If you want to just produce a simple class file,
  35. <code>javassist.bytecode.ClassFileWriter</code> might provide
  36. the best API for you. It is much faster than
  37. <code>javassist.bytecode.ClassFile</code> although its API
  38. is minimum.
  39. <a name="classfile">
  40. <h3>5.1 Obtaining a <code>ClassFile</code> object</h3>
  41. <p>A <code>javassist.bytecode.ClassFile</code> object represents
  42. a class file. To obtian this object, <code>getClassFile()</code>
  43. in <code>CtClass</code> should be called.
  44. <p>Otherwise, you can construct a
  45. <code>javassist.bytecode.ClassFile</code> directly from a class file.
  46. For example,
  47. <ul><pre>
  48. BufferedInputStream fin
  49. = new BufferedInputStream(new FileInputStream("Point.class"));
  50. ClassFile cf = new ClassFile(new DataInputStream(fin));
  51. </pre></ul>
  52. <p>
  53. This code snippet creats a <code>ClassFile</code> object from
  54. <code>Point.class</code>.
  55. <p>
  56. A <code>ClassFile</code> object can be written back to a
  57. class file. <code>write()</code> in <code>ClassFile</code>
  58. writes the contents of the class file to a given
  59. <code>DataOutputStream</code>.
  60. <p>You can create a new class file from scratch. For example,
  61. <blockquote><pre>
  62. ClassFile cf = new ClassFile(false, "test.Foo", null);
  63. cf.setInterfaces(new String[] { "java.lang.Cloneable" });
  64. FieldInfo f = new FieldInfo(cf.getConstPool(), "width", "I");
  65. f.setAccessFlags(AccessFlag.PUBLIC);
  66. cf.addField(f);
  67. cf.write(new DataOutputStream(new FileOutputStream("Foo.class")));
  68. </pre></blockquote>
  69. <p>this code generates a class file <code>Foo.class</code> that contains
  70. the implementation of the following class:
  71. <blockquote><pre>
  72. package test;
  73. class Foo implements Cloneable {
  74. public int width;
  75. }
  76. </pre></blockquote>
  77. <p><br>
  78. <a name="member">
  79. <h3>5.2 Adding and removing a member</h3>
  80. <p>
  81. <code>ClassFile</code> provides <code>addField()</code> and
  82. <code>addMethod()</code> for adding a field or a method (note that
  83. a constructor is regarded as a method at the bytecode level).
  84. It also provides <code>addAttribute()</code> for adding an attribute
  85. to the class file.
  86. <p>
  87. Note that <code>FieldInfo</code>, <code>MethodInfo</code>, and
  88. <code>AttributeInfo</code> objects include a link to a
  89. <code>ConstPool</code> (constant pool table) object. The <code>ConstPool</code>
  90. object must be common to the <code>ClassFile</code> object and
  91. a <code>FieldInfo</code> (or <code>MethodInfo</code> etc.) object
  92. that is added to that <code>ClassFile</code> object.
  93. In other words, a <code>FieldInfo</code> (or <code>MethodInfo</code> etc.) object
  94. must not be shared among different <code>ClassFile</code> objects.
  95. <p>
  96. To remove a field or a method from a <code>ClassFile</code> object,
  97. you must first obtain a <code>java.util.List</code>
  98. object containing all the fields of the class. <code>getFields()</code>
  99. and <code>getMethods()</code> return the lists. A field or a method can
  100. be removed by calling <code>remove()</code> on the <code>List</code> object.
  101. An attribute can be removed in a similar way.
  102. Call <code>getAttributes()</code> in <code>FieldInfo</code> or
  103. <code>MethodInfo</code> to obtain the list of attributes,
  104. and remove one from the list.
  105. <p><br>
  106. <a name="traverse">
  107. <h3>5.3 Traversing a method body</h3>
  108. <p>
  109. To examine every bytecode instruction in a method body,
  110. <code>CodeIterator</code> is useful. To otbain this object,
  111. do as follows:
  112. <ul><pre>
  113. ClassFile cf = ... ;
  114. MethodInfo minfo = cf.getMethod("move"); // we assume move is not overloaded.
  115. CodeAttribute ca = minfo.getCodeAttribute();
  116. CodeIterator i = ca.iterator();
  117. </pre></ul>
  118. <p>
  119. A <code>CodeIterator</code> object allows you to visit every
  120. bytecode instruction one by one from the beginning to the end.
  121. The following methods are part of the methods declared in
  122. <code>CodeIterator</code>:
  123. <ul>
  124. <li><code>void begin()</code><br>
  125. Move to the first instruction.<br>
  126. <li><code>void move(int index)</code><br>
  127. Move to the instruction specified by the given index.<br>
  128. <li><code>boolean hasNext()</code><br>
  129. Returns true if there is more instructions.<br>
  130. <li><code>int next()</code><br>
  131. Returns the index of the next instruction.<br>
  132. <em>Note that it does not return the opcode of the next
  133. instruction.</em><br>
  134. <li><code>int byteAt(int index)</code><br>
  135. Returns the unsigned 8bit value at the index.<br>
  136. <li><code>int u16bitAt(int index)</code><br>
  137. Returns the unsigned 16bit value at the index.<br>
  138. <li><code>int write(byte[] code, int index)</code><br>
  139. Writes a byte array at the index.<br>
  140. <li><code>void insert(int index, byte[] code)</code><br>
  141. Inserts a byte array at the index.
  142. Branch offsets etc. are automatically adjusted.<br>
  143. </ul>
  144. <p>The following code snippet displays all the instructions included
  145. in a method body:
  146. <ul><pre>
  147. CodeIterator ci = ... ;
  148. while (ci.hasNext()) {
  149. int index = ci.next();
  150. int op = ci.byteAt(index);
  151. System.out.println(Mnemonic.OPCODE[op]);
  152. }
  153. </pre></ul>
  154. <p><br>
  155. <a name="bytecode">
  156. <h3>5.4 Producing a bytecode sequence</h3>
  157. <p>
  158. A <code>Bytecode</code> object represents a sequence of bytecode
  159. instructions. It is a growable array of bytecode.
  160. Here is a sample code snippet:
  161. <ul><pre>
  162. ConstPool cp = ...; // constant pool table
  163. Bytecode b = new Bytecode(cp, 1, 0);
  164. b.addIconst(3);
  165. b.addReturn(CtClass.intType);
  166. CodeAttribute ca = b.toCodeAttribute();
  167. </pre></ul>
  168. <p>
  169. This produces the code attribute representing the following sequence:
  170. <ul><pre>
  171. iconst_3
  172. ireturn
  173. </pre></ul>
  174. <p>
  175. You can also obtain a byte array containing this sequence by
  176. calling <code>get()</code> in <code>Bytecode</code>. The
  177. obtained array can be inserted in another code attribute.
  178. <p>
  179. While <code>Bytecode</code> provides a number of methods for adding a
  180. specific instruction to the sequence, it provides
  181. <code>addOpcode()</code> for adding an 8bit opcode and
  182. <code>addIndex()</code> for adding an index.
  183. The 8bit value of each opcode is defined in the <code>Opcode</code>
  184. interface.
  185. <p>
  186. <code>addOpcode()</code> and other methods for adding a specific
  187. instruction are automatically maintain the maximum stack depth
  188. unless the control flow does not include a branch.
  189. This value can be obtained by calling <code>getMaxStack()</code>
  190. on the <code>Bytecode</code> object.
  191. It is also reflected on the <code>CodeAttribute</code> object
  192. constructed from the <code>Bytecode</code> object.
  193. To recompute the maximum stack depth of a method body,
  194. call <code>computeMaxStack()</code> in <code>CodeAttribute</code>.
  195. <p><code>Bytecode</code> can be used to construct a method.
  196. For example,
  197. <blockquote><pre>
  198. ClassFile cf = ...
  199. Bytecode code = new Bytecode(cf.getConstPool());
  200. code.addAload(0);
  201. code.addInvokespecial("java/lang/Object", MethodInfo.nameInit, "()V");
  202. code.addReturn(null);
  203. code.setMaxLocals(1);
  204. MethodInfo minfo = new MethodInfo(cf.getConstPool(), MethodInfo.nameInit, "()V");
  205. minfo.setCodeAttribute(code.toCodeAttribute());
  206. cf.addMethod(minfo);
  207. </pre></blockquote>
  208. <p>this code makes the default constructor and adds it to the class specified
  209. by <code>cf</code>. The <code>Bytecode</code> object is first converted into
  210. a <code>CodeAttribute</code> object and then added to the method specified
  211. by <code>minfo</code>. The method is finally added to a class file <code>cf</code>.
  212. <p><br>
  213. <a name="annotation">
  214. <h3>5.5 Annotations (Meta tags)</h3>
  215. <p>Annotations are stored in a class file
  216. as runtime invisible (or visible) annotations attribute.
  217. These attributes can be obtained from <code>ClassFile</code>,
  218. <code>MethodInfo</code>, or <code>FieldInfo</code> objects.
  219. Call <code>getAttribute(AnnotationsAttribute.invisibleTag)</code>
  220. on those objects. For more details, see the javadoc manual
  221. of <code>javassist.bytecode.AnnotationsAttribute</code> class
  222. and the <code>javassist.bytecode.annotation</code> package.
  223. <p>Javassist also let you access annotations by the higher-level
  224. API.
  225. If you want to access annotations through <code>CtClass</code>,
  226. call <code>getAnnotations()</code> in <code>CtClass</code> or
  227. <code>CtBehavior</code>.
  228. <p><br>
  229. <h2><a name="generics">6. Generics</a></h2>
  230. <p>The lower-level API of Javassist fully supports generics
  231. introduced by Java 5. On the other hand, the higher-level
  232. API such as <code>CtClass</code> does not directly support
  233. generics. However, this is not a serious problem for bytecode
  234. transformation.
  235. <p>The generics of Java is implemented by the erasure technique.
  236. After compilation, all type parameters are dropped off. For
  237. example, suppose that your source code declares a parameterized
  238. type <code>Vector&lt;String&gt;</code>:
  239. <ul><pre>
  240. Vector&lt;String&gt; v = new Vector&lt;String&gt();
  241. :
  242. String s = v.get(0);
  243. </pre></ul>
  244. <p>The compiled bytecode is equivalent to the following code:
  245. <ul><pre>
  246. Vector v = new Vector();
  247. :
  248. String s = (String)v.get(0);
  249. </pre></ul>
  250. <p>So when you write a bytecode transformer, you can just drop
  251. off all type parameters. Because the compiler embedded in Javassist
  252. does not support generics,
  253. you must insert an explicit type cast at the
  254. caller site if the source code is compiled by Javassist, for example,
  255. through <code>CtMethod.make()</code>. No type cast
  256. is necessary if the source code is compiled by a normal Java compiler
  257. such as <code>javac</code>.
  258. <p>For example, if you have a class:
  259. <ul><pre>
  260. public class Wrapper&lt;T&gt; {
  261. T value;
  262. public Wrapper(T t) { value = t; }
  263. }
  264. </pre></ul>
  265. <p>and want to add an interface <code>Getter&lt;T&gt;</code> to the
  266. class <code>Wrapper&lt;T&gt;</code>:
  267. <ul><pre>
  268. public interface Getter&lt;T&gt; {
  269. T get();
  270. }
  271. </pre></ul>
  272. <p>then the interface you really have to add is <code>Getter</code>
  273. (the type parameters <code>&lt;T&gt;</code> drops off)
  274. and the method you also have to add to the <code>Wrapper</code>
  275. class is this simple one:
  276. <ul><pre>
  277. public Object get() { return value; }
  278. </pre></ul>
  279. <p>Note that no type parameters are necessary.
  280. Since <code>get</code> returns an <code>Object</code>, an explicit type cast
  281. is needed at the caller site if the source code is compiled by Javassist.
  282. For example, if the type parameter <code>T</code>
  283. is <code>String</code>, then <code>(String)</code> must be inserted as follows:
  284. <ul><pre>
  285. Wrapper w = ...
  286. String s = (String)w.get();
  287. </pre></ul>
  288. <p>The type cast is not needed if the source code is compiled by a normal Java
  289. compiler because it will automatically insert a type cast.
  290. <p>If you need to make type parameters accessible through reflection
  291. during runtime, you have to add generic signatures to the class file.
  292. For more details, see the API documentation (javadoc) of the
  293. <code>setGenericSignature</code> method in the <code>CtClass</code>.
  294. <p><br>
  295. <h2><a name="varargs">7. Varargs</a></h2>
  296. <p>Currently, Javassist does not directly support varargs. So to make a method with varargs,
  297. you must explicitly set a method modifier. But this is easy.
  298. Suppose that now you want to make the following method:
  299. <ul><pre>
  300. public int length(int... args) { return args.length; }
  301. </pre></ul>
  302. <p>The following code using Javassist will make the method shown above:
  303. <ul><pre>
  304. CtClass cc = /* target class */;
  305. CtMethod m = CtMethod.make("public int length(int[] args) { return args.length; }", cc);
  306. m.setModifiers(m.getModifiers() | Modifier.VARARGS);
  307. cc.addMethod(m);
  308. <pre></ul>
  309. <p>The parameter type <code>int...</code> is changed into <code>int[]</code>
  310. and <code>Modifier.VARARGS</code> is added to the method modifiers.
  311. <p>To call this method in the source code compiled by the compiler embedded in Javassist,
  312. you must write:
  313. <ul><pre>
  314. length(new int[] { 1, 2, 3 });
  315. </pre></ul>
  316. <p>instead of this method call using the varargs mechanism:
  317. <ul><pre>
  318. length(1, 2, 3);
  319. </pre></ul>
  320. <p><br>
  321. <h2><a name="j2me">8. J2ME</a></h2>
  322. <p>If you modify a class file for the J2ME execution environment,
  323. you must perform <it>preverification</it>. Preverifying is basically
  324. producing stack maps, which is similar to stack map tables introduced
  325. into J2SE at JDK 1.6. Javassist maintains the stack maps for J2ME only if
  326. <code>javassist.bytecode.MethodInfo.doPreverify</code> is true.
  327. <p>You can also manually
  328. produce a stack map for a modified method.
  329. For a given method represented by a <code>CtMethod</code> object <code>m</code>,
  330. you can produce a stack map by calling the following methods:
  331. <ul><pre>
  332. m.getMethodInfo().rebuildStackMapForME(cpool);
  333. </pre></ul>
  334. <p>Here, <code>cpool</code> is a <code>ClassPool</code> object, which is
  335. available by calling <code>getClassPool()</code> on a <code>CtClass</code>
  336. object. A <code>ClassPool</code> object is responsible for finding
  337. class files from given class pathes. To obtain all the <code>CtMethod</code>
  338. objects, call the <code>getDeclaredMethods</code> method on a <code>CtClass</code> object.
  339. <p><br>
  340. <h2><a name="boxing">9. Boxing/Unboxing</h2>
  341. <p>Boxing and unboxing in Java are syntactic sugar. There is no bytecode for
  342. boxing or unboxing. So the compiler of Javassist does not support them.
  343. For example, the following statement is valid in Java:
  344. <ul><pre>
  345. Integer i = 3;
  346. </pre></ul>
  347. <p>since boxing is implicitly performed. For Javassist, however, you must explicitly
  348. convert a value type from <code>int</code> to <code>Integer</code>:
  349. <ul><pre>
  350. Integer i = new Integer(3);
  351. </pre></ul>
  352. <p><br>
  353. <h2><a name="debug">10. Debug</h2>
  354. <p>Set <code>CtClass.debugDump</code> to a directory name.
  355. Then all class files modified and generated by Javassist are saved in that
  356. directory. To stop this, set <code>CtClass.debugDump</code> to null.
  357. The default value is null.
  358. <p>For example,
  359. <ul><pre>
  360. CtClass.debugDump = "./dump";
  361. </pre></ul>
  362. <p>All modified class files are saved in <code>./dump</code>.
  363. <p><br>
  364. <a href="tutorial2.html">Previous page</a>
  365. <hr>
  366. Java(TM) is a trademark of Sun Microsystems, Inc.<br>
  367. Copyright (C) 2000-2015 by Shigeru Chiba, All rights reserved.
  368. </body>
  369. </html>