最近看了Java 編程的動態(tài)性,第 7 部分: 用 BCEL 設計字節(jié)碼,網(wǎng)址是http://www-128.ibm.com/developerworks/cn/java/j-dyn0414/
其中的示范代碼解釋的不是很詳細,這方面的中文資料又少,只好自己花時間看下去。bcel的類庫卻是不夠友好,api文檔也是走馬觀花的點一下,很多函數(shù)沒有說明。理解基本靠猜,還好有個示范代碼。下面對自己理解的東西做個記錄,詳細的代碼可以到上面的鏈接下載。
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.bcel.Constants;
import org.apache.bcel.classfile.ClassParser;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.generic.ClassGen;
import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.InstructionConstants;
import org.apache.bcel.generic.InstructionFactory;
import org.apache.bcel.generic.InstructionList;
import org.apache.bcel.generic.MethodGen;
import org.apache.bcel.generic.ObjectType;
import org.apache.bcel.generic.PUSH;
import org.apache.bcel.generic.Type;
public class BCELTiming {
??? /**
???? * Add timing wrapper to method of class. The method can accept any
???? * arguments and return any type (including void), but must be a normal
???? * (non-static, non-initializer) method to be used with this code as
???? * currently implemented. Handling the other types of methods would not
???? * involve any fundamental changes to the code.
???? *
???? * @param cgen
???? *??????????? generator for class being modified
???? * @param method
???? *??????????? current method to be enhanced with timing wrapper
???? */
??? private static void addWrapper(ClassGen cgen, Method method) {
??????? // set up the construction tools
??????? InstructionFactory ifact = new InstructionFactory(cgen);
??????? InstructionList ilist = new InstructionList();
??????? ConstantPoolGen pgen = cgen.getConstantPool();
??????? String cname = cgen.getClassName();
??????? MethodGen wrapgen = new MethodGen(method, cname, pgen);
??????? wrapgen.setInstructionList(ilist);
??????? // rename a copy of the original method
??????? MethodGen methgen = new MethodGen(method, cname, pgen);
??????? cgen.removeMethod(method);
??????? String iname = methgen.getName() + "$impl";
??????? methgen.setName(iname);
??????? cgen.addMethod(methgen.getMethod());
??????? //以上是一下初始化的工作
???????
??????? // compute the size of the calling parameters
??????? // operand stack操作數(shù)堆棧
??????? Type[] types = methgen.getArgumentTypes(); // 取出參數(shù)類型數(shù)組
??????? // solt代表本地變量的堆棧偏移量,里頭儲存了調用methen代表的函數(shù)的參數(shù)
??????? int slot = methgen.isStatic() ? 0 : 1; // 這種方式與Java如何處理方法調用有關。對于非靜態(tài)的方法,每次調用的第一個(隱藏的)參數(shù)是目標對象的this引用(就是位置0儲存的內(nèi)容)。
??????? for (int i = 0; i < types.length; i++) {
??????????? slot += types[i].getSize();// 累計個個參數(shù)類型的長度,
??????? }
??????? // 現(xiàn)在solt指向最后一個參數(shù)的下一個位置
??????? // save time prior to invocation
??????? // 調用靜態(tài)的long java.lang.System.currentTimeMillis()方法,調用結束后函數(shù)的返回的long類型的值會壓入operand stack操作數(shù)堆棧
??????? ilist.append(ifact.createInvoke("java.lang.System",
??????????????? "currentTimeMillis", Type.LONG, Type.NO_ARGS,
??????????????? Constants.INVOKESTATIC));
??????? ilist.append(InstructionFactory.createStore(Type.LONG, slot));// 將operand stack的top保存到本地變量堆棧的slot位置,operand stack彈出long值
??????? // call the wrapped method
??????? int offset = 0; // 偏移量
??????? short invoke = Constants.INVOKESTATIC; // 預先設置為調用靜態(tài)函數(shù)
??????? if (!methgen.isStatic()) { // 如果不是調用靜態(tài)函數(shù),將調用的第一個(隱藏的)參數(shù)(目標對象的this引用)壓入operand stack
??????????? ilist.append(InstructionFactory.createLoad(Type.OBJECT, 0));
??????????? offset = 1;// 偏移量加1
??????????? invoke = Constants.INVOKEVIRTUAL;// 設置為調用非靜態(tài)函數(shù)
??????? }
??????? for (int i = 0; i < types.length; i++) { // 遍歷所有參數(shù)
??????????? Type type = types[i];
??????????? ilist.append(InstructionFactory.createLoad(type, offset)); // 按參數(shù)類型把參數(shù)一個個從本地變量堆棧取出,壓入operand stack
??????????? offset += type.getSize();
??????? }
??????? Type result = methgen.getReturnType();// 取得要調用函數(shù)的返回值類型
??????? ilist.append(ifact.createInvoke(cname, iname, result, types, invoke));// 調用方法名為iname的函數(shù)
??????? // store result for return later
??????? if (result != Type.VOID) {
??????????? ilist.append(InstructionFactory.createStore(result, slot + 2)); // 將名為iname的函數(shù)返回值復制到本地變量堆棧的slot+2的位置上
??????? }
??????? // print time required for method call
??????? // 獲取靜態(tài)對象java.lang.System.out的引用,返回值壓入operand stack
??????? ilist.append(ifact.createFieldAccess("java.lang.System", "out",
??????????????? new ObjectType("java.io.PrintStream"), Constants.GETSTATIC));
??????? ilist.append(InstructionConstants.DUP);// 取operand stack的top,壓入operand stack。完成后load_stack的頭兩個元素是靜態(tài)對象java.lang.System.out的引用
??????? ilist.append(InstructionConstants.DUP);// 取operand stack的top,壓入operand stack。現(xiàn)在有3個java.lang.System.out的引用。供下面3次調用out.print()函數(shù)使用
??????? String text = "Call to method " + methgen.getName() + " took ";
??????? ilist.append(new PUSH(pgen, text));// 將text放入pgen(代表常量池),并把其在pgen的引用壓入operand stack(供out.print(Sting)調用的參數(shù))
??????? ilist.append(ifact.createInvoke("java.io.PrintStream", "print",
??????????????????????? Type.VOID, new Type[] { Type.STRING },
??????????????????????? Constants.INVOKEVIRTUAL));// 調用結束,operand stack彈出一個String的引用和一個out的引用(還剩2個out),函數(shù)沒有返回值
??????? ilist.append(ifact.createInvoke("java.lang.System",
??????????????? "currentTimeMillis", Type.LONG, Type.NO_ARGS,
??????????????? Constants.INVOKESTATIC));// 調用java.lang.System.currentTimeMillis()方法,調用結束后函數(shù)的返回的long類型的值會壓入堆棧operand stack
??????? ilist.append(InstructionFactory.createLoad(Type.LONG, slot));// 從本地變量堆棧的slot位置載入先前儲存的long值,壓入operand stack
??????? ilist.append(InstructionConstants.LSUB);// 調用long的減法指令,彈出2個long值,并把結果壓入operand stack,現(xiàn)在operand stack的top第一個是long,第二個是out的引用
??????? ilist.append(ifact.createInvoke("java.io.PrintStream", "print",
??????????????? Type.VOID, new Type[] { Type.LONG }, Constants.INVOKEVIRTUAL));// 調用out.print(long)方法
??????? ilist.append(new PUSH(pgen, " ms."));// 將String對象" ms."放入pgen,并把其在pgen的引用壓入operand stack(供out.print(Sting)調用的參數(shù))
??????? ilist
??????????????? .append(ifact.createInvoke("java.io.PrintStream", "println",
??????????????????????? Type.VOID, new Type[] { Type.STRING },
??????????????????????? Constants.INVOKEVIRTUAL));
??????? // return result from wrapped method call
??????? if (result != Type.VOID) {
??????????? ilist.append(InstructionFactory.createLoad(result, slot + 2));// 處理返回值,如果不為空,從本地對象堆棧的slot+2位置讀取指定類型的返回值壓入operand stack
??????? }
??????? ilist.append(InstructionFactory.createReturn(result)); //調用處理返回值的指令,result為返回值的類型
??????? //下面是一下掃尾工作
??????? // finalize the constructed method
??????? wrapgen.stripAttributes(true);
??????? wrapgen.setMaxStack();
??????? wrapgen.setMaxLocals();
??????? cgen.addMethod(wrapgen.getMethod());
??????? ilist.dispose();
??? }
??? public static void main(String[] argv) {
??????? if (argv.length == 2 && argv[0].endsWith(".class")) {
??????????? try {
??????????????? JavaClass jclas = new ClassParser(argv[0]).parse();
??????????????? ClassGen cgen = new ClassGen(jclas);
??????????????? Method[] methods = jclas.getMethods();
??????????????? int index;
??????????????? for (index = 0; index < methods.length; index++) {
??????????????????? if (methods[index].getName().equals(argv[1])) {
??????????????????????? break;
??????????????????? }
??????????????? }
??????????????? if (index < methods.length) {
??????????????????? addWrapper(cgen, methods[index]);
??????????????????? FileOutputStream fos = new FileOutputStream(argv[0]);
??????????????????? cgen.getJavaClass().dump(fos);
??????????????????? fos.close();
??????????????? } else {
??????????????????? System.err.println("Method " + argv[1] + " not found in "
??????????????????????????? + argv[0]);
??????????????? }
??????????? } catch (IOException ex) {
??????????????? ex.printStackTrace(System.err);
??????????? }
??????? } else {
??????????? System.out.println("Usage: BCELTiming class-file method-name");
??????? }
??? }
}
相對javassist,bcel確實比較復雜。但是bcel給我的感覺比較自由,有種一切盡在掌握的感覺,這一點比較我喜歡。
雖然自由,但是用bcel寫一個類的實現(xiàn)絕對不會是一件讓人開心的事情,如果碰巧你的實現(xiàn)又稍微復雜了點(比如實現(xiàn)了xx接口,又增加了一些函數(shù)和成員變量)。而且你的實現(xiàn)未必會比javac編譯出來的代碼效率高(不考慮jvm的動態(tài)優(yōu)化)。
不過,先把你要實現(xiàn)的類的代碼寫出來,按照代碼來寫bcel的實現(xiàn),會降低些實現(xiàn)難度。
posted on 2006-05-31 16:44
含笑半步癲 閱讀(2459)
評論(4) 編輯 收藏 引用 所屬分類:
java