且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

可以使用ByteBuddy代替调用的方法来检测方法调用吗?

更新时间:2022-06-16 23:30:01

您当前可以通过注册 MemberSubstitution 来替换方法或字段访问,但是与AspectJ相比,该功能仍然受到限制.例如,不可能像示例代码中那样引发异常.但是,您可以委派一个方法,该方法包含引发异常的代码:

You can currently replace a method or field access by registering a MemberSubstitution but the capabilities are still limited compared to AspectJ. It is for example not possible to throw an exception as in your example code. You can however delegate to a method that would contain the code that throws the exception:

MemberSubstitution.relaxed()
  .method(named("currentTimeMillis"))
  .replaceWith(MyClass.class.getMethod("throwException"))
  .in(any());

上面的替换将用对以下成员的调用替换任何方法调用:

The above substitution would replace any method call with a call to the following member:

public class MyClass {
  public static long throwException() {
    throw new IllegalStateException();
  }
}

该替换将应用于访问者所应用的任何方法.您可以注册 AgentBuilder.Default 来构建Java代理来这样做,也可以查看Byte Buddy的构建插件.

The substitution would be applied to any method onto which the visitor is applied. You can register an AgentBuilder.Default to build a Java agent to do so or have a look into Byte Buddy's build plugins.