gpt4 book ai didi

java - 无法看到 BCEL 所做的更改

转载 作者:行者123 更新时间:2023-12-01 05:36:03 25 4
gpt4 key购买 nike

我正在尝试使用 BCEL 更改我的测试类的主要方法。我只想添加 System.out.println("这是 BCEL 在运行时添加的")到 main() 的开头。尽管我没有收到异常并且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();
}
}
}

最佳答案

终于发现错误了。我不知道我必须打电话cg.replaceMethod(m, mg.getMethod()); 将我的更改保存在类文件中。

关于java - 无法看到 BCEL 所做的更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8194662/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com