Search code examples
byte-buddy

How do I use MethodCall.invoke(someElementMatcher) to create a MethodCall representing a method I subsequently define in an instrumented type?


I am using ByteBuddy to generate a class.

Prior to working with DynamicType.Builder, I was going to store a MethodCall as an instance variable:

private final MethodCall frobCall =
  MethodCall.invoke(ElementMatchers.named("frob")); // here I invoke a method I'm going to define as part of the instrumented type

Then later in my generation logic for the instrumented type I define the frob method to do something:

.defineMethod("frob")
.intercept(...etc....) // here I define frob to do something

…and I define the (let's say) baz method to invoke frob:

.defineMethod("baz")
.withParameter(...) // etc.
.intercept(frobCall); // invokes "frob", which I've just defined above

(I am trying to keep this simple and may have mistyped something but I hope you can see the gist of what I'm trying to do.)

When I make() my DynamicType, I receive an error that indicates that the dynamic type does not define frob. This is mystifying to me, because of course I have defined it, as you can see above.

Is there some restriction I am unaware of that prohibits ElementMatchers from identifying instrumented type methods that are defined later? Do I really have to use MethodDescription.Latent here?


Solution

  • It should match all methods of the instrumented type. If this is not happening as expected, please set a breakpoint in MethodCall.MethodLocator.ForElementMatcher to see why the method is not showing up. I assume it is filtered by your method matcher.

    I noticed however that it did not include private methods which is now fixed and will be released within Byte Buddy 1.10.18.