Reputation: 4642
I am exploring ByteBuddy for a project of mine. I am trying to intercept an annotated method as:
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.dynamic.loading.ClassLoadingStrategy.Default;
import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.matcher.ElementMatchers;
public class Fibonacci {
public static void main(String[] args) throws IllegalAccessException, InstantiationException {
Fibonacci fibonacci =
new ByteBuddy()
.subclass(Fibonacci.class)
.method(ElementMatchers.isAnnotatedWith(PreCondition.class))
.intercept(MethodDelegation.to(new FiboAgent()))
.make()
.load(Fibonacci.class.getClassLoader(), Default.WRAPPER)
.getLoaded()
.newInstance();
fibonacci.printFibo(5);
}
@PreCondition(expression = "n > 5")
public void printFibo(Integer i) {
System.out.println("Here");
}
}
FiboAgent.java:
import net.bytebuddy.asm.Advice.AllArguments;
public class FiboAgent {
public void intercept(@AllArguments Object[] args) {
System.out.println("Intercepted");
}
}
I am not able to figure out why this doesn't work.
ByteBuddy version: 1.10.19
Upvotes: 1
Views: 691
Reputation: 43972
This is unfortunately simple error to make. There is a difference between Advice and MethodDelegation. Method delegation is more powerful but also more intrusive on a byte code level what makes it less attractive to Java agents which often cannot add members. To make it simpler to switch between the two, the annotations are aligned since advice covers a subset of the delegation functionality. If you replace:
import net.bytebuddy.asm.Advice.AllArguments;
with
import net.bytebuddy.implementation.bind.annotation.AllArguments;
everything should work as expected.
Upvotes: 2