我正在尝试在源自另一个项目的 jar 的类的方法主体的开头插入代码片段。 在当前的项目中,我正在使用 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(),
我可以验证显然正在进行更改,但在调用该方法时并未加载。
执行方法时调用我的修改缺少什么?
谢谢。
最佳答案
我通过更改解决了设置字节码类的问题。 这是解决方案的代码:
if(method.getName().equals("insereVendaCabecalhoTrocaDevolucao")){
method.insertBefore("{pVendaCabecalho.setCupomSat(java.lang.Boolean.FALSE);}");
byteCode = vendaControllerCt.toBytecode();
}
谢谢。
关于java - 如何使用 Javassist 在 ChMethod 中使用 insertBefore () 加载修改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45238483/