• <ins id="pjuwb"></ins>
    <blockquote id="pjuwb"><pre id="pjuwb"></pre></blockquote>
    <noscript id="pjuwb"></noscript>
          <sup id="pjuwb"><pre id="pjuwb"></pre></sup>
            <dd id="pjuwb"></dd>
            <abbr id="pjuwb"></abbr>
            隨筆-30  評論-67  文章-0  trackbacks-0

            最近看了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

            評論:
            # re: 學用BCEL設計字節(jié)碼的記錄(java) 2006-08-31 09:41 | lai
            我嘗試了編譯這個程序,可是沒有輸出啊!估計是因為在StringBuilder中沒有傳進參數(shù)的原因,請問在eclipse中應該怎么做呢
              回復  更多評論
              
            # re: 學用BCEL設計字節(jié)碼的記錄(java) 2006-09-07 22:47 | 含笑半步癲
            main的函數(shù)是需要參數(shù)的。具體如何運行請參考上面給出的ibm的文章  回復  更多評論
              
            # re: 學用BCEL設計字節(jié)碼的記錄(java) 2008-01-04 17:52 | allen
            這個代碼好像是丹尼斯寫的 IBM網(wǎng)站Java動態(tài)編程系列文章一共8篇  回復  更多評論
              
            # re: 學用BCEL設計字節(jié)碼的記錄(java) 2010-05-20 15:16 | ewwerpm
            包org.apache.bcel.util.BCELifier和com.sun.org.apache.bcel.internal.util.BCELifier有什么區(qū)別?com.sun.org.apache.bcel.internal.util.BCELifier是裝 JDK1.6的時候JRE里面自帶的,org.apache.bcel.util.BCELifier需要從網(wǎng)上下載,類名字是一樣的,不知道他們在使用的時候有什么區(qū)別?我只能用org.apache.bcel.util.BCELifier包將HelloWorld.class文件反編譯成HelloWorldCreator.java文件,但是在執(zhí)行 java HelloWorldCrator 的時候沒用設想中的輸出啊。
            public class HelloWorld{
            public static void main(String args[]){
            System.err.println("Hello World through BCEL!");
            }
            }  回復  更多評論
              
            亚洲AV无码久久精品蜜桃| 理论片午午伦夜理片久久 | 亚洲Av无码国产情品久久| 污污内射久久一区二区欧美日韩| 久久亚洲AV无码西西人体| 97久久婷婷五月综合色d啪蜜芽 | 精品久久久久一区二区三区 | 色偷偷88888欧美精品久久久| 亚洲欧美成人综合久久久| 精品熟女少妇av免费久久| 国产亚洲色婷婷久久99精品91| 国产精品久久久久a影院| 久久久久久无码Av成人影院| 久久久无码精品午夜| 久久人人妻人人爽人人爽| Xx性欧美肥妇精品久久久久久| 一本久久综合亚洲鲁鲁五月天亚洲欧美一区二区 | 久久99热狠狠色精品一区| 性做久久久久久免费观看| 国产精品美女久久久m| 综合久久精品色| 久久精品二区| 99精品国产在热久久| 久久婷婷人人澡人人爽人人爱| 久久国产热这里只有精品| 久久99国产精一区二区三区| 东方aⅴ免费观看久久av| 伊人精品久久久久7777| 国产精品成人99久久久久| av无码久久久久久不卡网站| 亚洲国产日韩欧美综合久久| 国产亚洲成人久久| 91麻豆精品国产91久久久久久| 国产精品无码久久综合| 人妻精品久久久久中文字幕69 | 一本一本久久aa综合精品| 久久综合伊人77777| 亚洲国产天堂久久综合| 亚洲国产成人精品久久久国产成人一区二区三区综 | 免费国产99久久久香蕉| 久久―日本道色综合久久|