![](/img/trans.png)
[英]How can I instrument/intercept Method.invoke in a ByteBuddy agent?
[英]Can I instrument outgoing method/constructor calls with ByteBuddy?
我有一个项目,我在其中使用Javassist使用如下代码记录传出的方法/构造函数调用:
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
:
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吗?
这个问题与另一个问题有关,该问题要求一种捕获构造函数异常的方法,因为这是我使用Javassist实现的方法。
您可以使用“ Advice
来更改方法的参数,该Advice
可让您在执行原始方法之前更改参数:
@Advice.OnMethodEnter
static void enter(@Advice.Argument(value = 0, readOnly = false) int arg) {
arg = 0;
}
这样做,上面的代码将添加到您需要使用诸如named("move")
类的ElementMatcher
定位的move
方法之前。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.