简体   繁体   中英

ByteBuddy Method Interceptor With @AllArguments Doesn't Seem To Work

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM