简体   繁体   English

Java ASM 字节码操作 - 如何在方法中间注入?

[英]Java ASM Bytecode Manipulation - How to inject in middle of method?

Using ASM, how can i inject a method exactly where I want it to go?使用 ASM,我如何才能准确地将方法注入到我想要的位置?

example:例子:

public void exampleMethod() {
    doOneThing();
    doSomeMoreStuff();

    if (someCondition) {
        doEvenMoreThings();
    }

    callMyInjectedMethodHere(); // This call has been injected

    if (someOtherCondition) {
        doRandomStuff();
    }

    doStuff();
}

ASM has a visitor and a tree API which allows you to process a method's byte code instruction by instruction. ASM 有一个访问者和一个树 API,它允许您按指令处理方法的字节码指令。 What you would need to do would be to visit all instructions, in your case two method calls, a branching instruction, a method call and a label that is the target of the previous branch and then emitt an additional method call instruction.您需要做的是访问所有指令,在您的情况下是两个方法调用、一个分支指令、一个方法调用和一个标签,该标签是前一个分支的目标,然后发出一个额外的方法调用指令。 This way, you can modify the method.这样,您就可以修改该方法。

Do however notice that method bodies typically change more rapidly then signatures and that such injections tend to be very fragile.但是请注意,方法主体的变化通常比签名更快,并且这种注入往往非常脆弱。 If you can avoid it, avoid it.如果你能避免它,就避免它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM