Search code examples
javajava-bytecode-asmbyte-buddy

Intercepting method calls on the caller side


I need to intercept certain invocations with bytebuddy. However, the .intercept() API, as far as I can tell, edits the code on the callee side. I need it to be intercepted caller side. How can I achieve this? I have a list of all callers, and I can edit them, but is there an api for modifying the body of a function in this manner?


Solution

  • You can replace method calls using a MemberSubstitution. You apply this by registering via DynamicType.Builder::visit where you can decide what methods need adjustment. You can redirect the invocations to your own infrastructure and invoking the actual code if appropriate.

    That said, member substitution is limited, callee substitution is much more flexible. Possibly, use a StackWalker to locate your current position in the stack.