繁体   English   中英

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

[英]Can a method call be instrumented with ByteBuddy instead of the called method?

我想替换一些AspectJ代码,以防止某些用户代码对java.lang.System调用。 无法/不应检测java.lang.System

使用AspectJ,解决方案是像下面的示例那样检测调用代码。 应该保护的代码将被检测,而不允许的代码则不会。

@Around("call(public long java.lang.System.currentTimeMillis()) && within(io.someuserdomain..*) && !within(io.someotherdomain..*))
def aroundSystemcurrentTimeMillis(wrapped: ProceedingJoinPoint): Long = {
      throw new IllegalStateException("must not call System.currentTimeMillis in usercode")
}

有没有办法使用ByteBuddy做同样的事情? 到目前为止,我仅发现了有关如何为被调用方而不是调用方进行检测的示例。

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

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

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

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

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

暂无
暂无

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

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