Java: Inject code before and after method call

ThomasH :

I'm risking this question knowing quite a few other questions have been asked that somehow touch the same issue. But they are either quite old, or very specific, or hard to follow, and the answers are also very specific and seem not applicable to my use case.

What I want to achieve is quite simple to describe, it is about injecting code before and after a method call in Java. Here is a simple example. I want something like this line of code:

method(p1, @ANNOTATION(type=String) p2, p3);

to desugar to

Wrapper<String> w = new Wrapper<>(p2);
method(p1, w, p3);
p2 = w.get();

in the context of a larger block of statements, with a pre-defined Wrapper class. I have limited control over the build environment that is used to compile the code, so any solution should be realizable with Gradle plugins/dependencies.

What I've looked at so far (without having a deep understanding of any of them):

  • Java Annotations : are never seriously considered in answers to similar questions, so I guess they are incapable of achieving that
  • Aspect frameworks like AspectJ or Spring Aspects: are mentioned most often, but they only seem to be able to wrap entire methods, not specific invocations of them
  • Bytcode manipulation frameworks like asm or cglib: seem generally capable of doing this, but are quite heavy-weight and require some plumbing, esp. on the build side, to achieve it

So, what could be a solution for this?

ThomasH :

As ever so often on SO, answers are proposed in comments rather than in answers. So I'm picking from the comments above what appears to me as at least the most promising approach to pursue further:

Use a bytecode manipulation library like ASM or cglib.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=418238&siteId=1