Не вижу изменений, внесенных BCEL - PullRequest
1 голос
/ 19 ноября 2011

Я пытаюсь изменить основной метод моего класса Test, используя BCEL. Я просто хочу добавить System.out.println("This is added by BCEL at runtime") к началу основного (). Хотя я не получаю исключения и InstructionList показывает мои команды, моя строка не печатается, а javap -c показывает неизмененную версию. Вот мой код:

    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();
        }
    }
}

1 Ответ

0 голосов
/ 19 ноября 2011

Наконец, ошибка найдена. Я не знал, что мне нужно позвонить cg.replaceMethod(m, mg.getMethod()); чтобы сохранить мои изменения в файле класса.

...