我可以使用 ByteBuddy 检测传出方法/构造函数调用吗? [英] Can I instrument outgoing method/constructor calls with ByteBuddy?

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

问题描述

我有一个项目,我使用 Javassist 记录传出的方法/构造函数调用,代码如下:

I have a project where I was using Javassist to log outgoing method/constructor calls with code like this:

CtMethod cm = ... ;
cm.instrument(
new ExprEditor() {
    public void edit(MethodCall m)
                  throws CannotCompileException
    {
        if (m.getClassName().equals("Point")
                      && m.getMethodName().equals("move"))
            m.replace("{ $1 = 0; $_ = $proceed($$); }");
    }
});

将'0'分配给被调用方法的第一个参数,然后继续原始调用,即如果cm代表方法someMethod,我们修改从 someMethod 传出对 Point::move 的调用:

which assigns '0' to the first argument of the called method and then proceeds with the original call, that is, if cm represents the method someMethod we modify the outgoing calls to Point::move from someMethod:

public int someMethod(int arg1){        
    Point p;
    ...
    Point newPoint =
    //Here we start tampering with the code        
        p.move(0, arg2, arg3, arg4); //Say it was originally p.move(arg1, arg2, arg3, arg4);
    //From here we leave it as it was
    ...
}

我现在正在尝试迁移到 ByteBuddy,因为我希望这些类与(在线)JaCoCo 兼容.我已经设法从内部"检测方法和构造函数(检测被调用的方法本身),但我还没有找到任何从外部"检测的方法(检测从其他地方对此类方法的调用).有没有办法用 ByteBuddy 做到这一点?

I am now trying to migrate to ByteBuddy as I wanted the classes to be compatible with (online) JaCoCo. I've managed to instrument methods and constructors "from the inside" (instrumenting the called methods themselves), but I haven't found any way to do it "from the outside" (instrumenting the calls to such methods from elsewhere). Is there any way to do it with ByteBuddy ?

这个问题与另一个要求捕获构造函数异常的方法,因为这是我使用 Javassist 实现的方法.

This question is related to another which asked for a way to catch constructor exceptions as it is the way I achieved it using Javassist.

推荐答案

您可以通过使用 Advice 更改方法的参数,这允许您在原始方法执行之前更改参数:

You can change an argument of a method by using Advice which allows you to change an argument prior to the original method's execution:

@Advice.OnMethodEnter
static void enter(@Advice.Argument(value = 0, readOnly = false) int arg) {
  arg = 0;
}

这样做,上面的代码将被添加到 move 方法之前,您需要使用 ElementMatcher 来定位,例如 named("move").

Doing so, the above code will be prepended to the move method that you need to locate using an ElementMatcher like named("move").

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

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