我正在尝试在源自另一个项目的jar的类的方法体的开始处插入代码片段。 在这个当前项目中,我正在使用tha javassist库,使用它我能够找到并操作我想要修改的类和方法,因为我已经将这个旧项目的jar添加为当前库中的库。以下是我可以执行此操作的代码:
try {
ClassPool classPool = ClassPool.getDefault();
CtClass vendaControllerCt = classPool.getCtClass("com.t2tierp.pafecf.controller.VendaController");
CtMethod[] methods = vendaControllerCt.getMethods();
for(CtMethod method : methods){
if(method.getName().equals("insereVendaCabecalhoTrocaDevolucao")){
method.insertBefore("{pVendaCabecalho.setCupomSat(java.lang.Boolean.FALSE);");
}
}
} catch (NotFoundException e) {
e.printStackTrace();
} catch (CannotCompileException e) {
e.printStackTrace();
}
在本节中,一旦找到我想要修改的方法,名为insereVendaCabecalhoTrocaDevolucao
,我就会使用库方法insertBefore()
插入要重新调整的新行。但是当我执行项目并调用我修改的方法时,不会加载调整,并且在没有调整的情况下加载原始方法。
使用InstructionPrint.print(),
我可以验证显然正在进行更改,但在调用方法时未加载。
执行方法时调用的修改缺少什么?
感谢。
答案 0 :(得分:1)
我解决了使用更改设置字节码类的问题。 以下是解决方案的代码:
if(method.getName().equals("insereVendaCabecalhoTrocaDevolucao")){
method.insertBefore("{pVendaCabecalho.setCupomSat(java.lang.Boolean.FALSE);}");
byteCode = vendaControllerCt.toBytecode();
}
感谢。
答案 1 :(得分:0)
您需要在CtClass对象上调用writeFile
以保存文件中的更改。