首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >看不到BCEL所做的更改

看不到BCEL所做的更改
EN

Stack Overflow用户
提问于 2011-11-19 22:28:28
回答 1查看 318关注 0票数 1

我正在尝试使用BCEL更改我的Test类的main方法。我只想将System.out.println("This is added by BCEL at runtime")添加到main()的开头。虽然我没有收到异常,并且InstructionList显示了我的命令,但是我的字符串没有打印出来,javap -c显示的是未修改的版本。下面是我的代码:

代码语言:javascript
复制
    public static void main(String[] args) {
        try {
            JavaClass jc = Repository.lookupClass("Test");
            System.out.println("Found class" + jc.getClassName());
            ClassGen cg = new ClassGen(jc);
            ConstantPoolGen cpg = cg.getConstantPool();
            for (org.apache.bcel.classfile.Method m : jc.getMethods()) {
                if (m.getName().equals("main")) {
                    MethodGen mg = new MethodGen(m, cg.getClassName(), cpg);
                    InstructionList list = mg.getInstructionList();
                    int stringIndex = cpg.addString("This is added by BCEL at runtime");
                    System.out.println("String index = " + stringIndex);
                    int soutIndex = cpg.lookupFieldref("java.lang.System", "out", "Ljava/io/PrintStream;");
                    System.out.println("Sout index = " + soutIndex);
                    int printlnIndex = cpg.lookupMethodref("java.io.PrintStream", "println", "(Ljava/lang/String;)V");
                    System.out.println("Println index = " + printlnIndex);
                    InstructionList patch = new InstructionList();
                    patch.append(new GETSTATIC(soutIndex));
                    patch.append(new LDC(stringIndex));
                    patch.append(new INVOKEVIRTUAL(printlnIndex));
                    list.insert(list.getInstructionHandles()[0], patch);
                    mg.setMaxStack();

                    File f = new File(Repository.lookupClassFile(cg.getClassName()).getPath());
                    cg.getJavaClass().dump(f.getPath());
                    System.out.println(f.getPath());

                    for (InstructionHandle ih : list.getInstructionHandles()) {
                        System.out.println(ih.getInstruction().toString());
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
EN

回答 1

Stack Overflow用户

发布于 2011-11-19 23:05:57

最后,发现了错误。我不知道我必须调用cg.replaceMethod(m, mg.getMethod());来保存我在类文件中的更改。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8194662

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档