可以使用ByteBuddy代替调用的方法来检测方法调用吗? [英] Can a method call be instrumented with ByteBuddy instead of the called method?

查看:78
本文介绍了可以使用ByteBuddy代替调用的方法来检测方法调用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想替换一些AspectJ代码,以保护某些用户代码对 java.lang.System 的调用. java.lang.System 无法/不应被检测.

I would like to replace some AspectJ code that protects calls to java.lang.System from some user code. java.lang.System cannot/should not be instrumented.

使用AspectJ,解决方案是像下面的示例那样对调用代码进行检测.将保护应保护的代码,而不允许的代码将被检测.

With AspectJ the solution is to instrument the calling code like the following example. The code that should be guarded will be instrumented while the code that is allowed is not.

@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?到目前为止,我仅找到了有关如何为被呼叫者而不是呼叫者进行检测的示例.

Is there a way to do the same using ByteBuddy? So far I only found examples on how to instrument the callee instead of the caller.

推荐答案

您当前可以通过注册 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.

这篇关于可以使用ByteBuddy代替调用的方法来检测方法调用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆