I have seen many frameworks around that let you inject bytecode into Java classes at runtime. But in all of the examples and documentation, they just show how to inject BEFORE and AFTER methods. But I need to inject somewhere in the MIDDLE of a method. How do I do this?
Here is an example method I might want to inject into:
public void doSomething() {
doOneThing();
doSomeMoreStuff();
if (someCondition) {
doEvenMoreThings();
}
if (someOtherCondition) {
doRandomStuff();
}
doStuff();
}
I want to inject here
if (someOtherCondition) {
doRandomStuff();
// INJECT HERE
}
so that the fully transformed method looks something like this:
public void doSomething() {
doOneThing();
doSomeMoreStuff();
if (someCondition) {
doEvenMoreThings();
}
if (someOtherCondition) {
doRandomStuff();
callMyInjectedMethodHere(); // This call has been injected
}
doStuff();
}
Is this possible? If so, how?
Every framework I've ever seen has docs that would suggest I can only inject directly above doOneThing();
or directly below doStuff();
.
The framework you use doesn't really matter, any one you like that allows you to do this is a good answer for me.