简体   繁体   English

带有@AllArguments 的 ByteBuddy 方法拦截器似乎不起作用

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

I am exploring ByteBuddy for a project of mine.我正在为我的一个项目探索 ByteBuddy。 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: 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字节好友版本:1.10.19

This is unfortunately simple error to make.不幸的是,这是一个简单的错误。 There is a difference between Advice and MethodDelegation . AdviceMethodDelegation之间有区别。 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.方法委托更强大,但在字节码级别上也更具侵入性,这使得它对经常无法添加成员的 Java 代理的吸引力降低。 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.一切都应该按预期工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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