Can Byte Buddy access the name of a local variable of a method?

Suppose I have a method m :

 public void m() { String foo = "foo"; int bar = 0; doSomething(foo, bar); } 

I want to use ByteBuddy to encode the code so that when doSomething called in m it automatically doSomething value foo and bar in the HashMap , almost something similar:

 public void m() { String foo = "foo"; int bar = 0; context.put("foo", foo); // new code injected context.put("bar", bar); // new code injected doSomething(foo, bar); } 

Is there a way to do this with ByteBuddy?

+6
source share
1 answer

Byte Buddy has a built-in way to override the m method this way. Byte Buddy, however, voluntarily discloses the ASM API, on top of which Byte Buddy is implemented. ASM offers quite extensive documentation that will show you how to do this. However, I can say that it will be quite a lot of code. Note that you need to compile any method with debugging symbols turned on, otherwise these internal variables are not available at runtime.

Are you sure you want to do this? Not knowing your specific use case, it seems like a bad idea. By implementing this solution, you make local variable names part of your application, rather than letting them be implementation details.

Therefore, I suggest you rather use the doSomething method. Will it be enough, which is easy to do in Byte Buddy using an interceptor as shown below:

 class Interceptor { void intercept(@Origin Method method, @AllArguments Object[] args) { int index = 0; for(Parameter p : method.getParameters()) { context.add(p.getName(), args[index++]); } } } 

Then this interceptor can be used as follows:

 MethodDelegation.to(new Interceptor()).andThen(SuperMethodCall.INSTANCE); 
+1
source

Source: https://habr.com/ru/post/980817/


All Articles