0

I am solving a problem for a school work. let us say I have a class as follows

class test {

public String foo(int i) {
printvalue(i);
return "foo";
}

public void printvalue(int i) {
System.out.println(i);
}
}

class Solution {
  public static void main(String[] args) {

      System.out.println(new test().foo(10));
    }
  }

output is

10 foo

Now I'm creating a java agent which will intercept all calls to foo and I want to create a new method in bar as follows and replace all calls to foo to just call bar(int i) and then return.

public String bar(int i) {
printvalue(i);
return "bar";
}

so the output of main should change to

10 bar

How can I achieve this. I was looking to use bytebuddy or javassist to do this. Any help is appreciated

1 Answers1

0

This is possible in Byte Buddy by using a MemberSubstitution. In the DSL, you can write:

MemberSubstitution.relaxed()
  .method(ElementMatchers.named("foo"))
  .replaceWith(ElementMatchers.named("bar"))

You can register this visitor using an AgentBuilder that implements the agent.

You can implement a custom method using the builder DSL where you can provide the implementation as a combination of MethodCall and FixedValue.

Rafael Winterhalter
  • 42,759
  • 13
  • 108
  • 192