使用 insertAfter 在 Javassist 中检测构造函数

Instrumenting constructors in Javassist using insertAfter

我正在尝试让构造函数在被调用时打印出一些东西。我通过使用 insertAfter 来做到这一点。我还想打印出对象引用。我尝试使用 $_ 但它只是设置为 0。是否可以打印出新对象的对象引用?

我终于找到了我想要的解决方案。它包括使用这样的 ExprEditor

public CtClass instrumentMethods() throws CannotCompileException, IOException {
    ClassPool cp = ClassPool.getDefault();
    cp.insertClassPath(new LoaderClassPath(loader));
    CtClass ctKlazz = cp.makeClass(instream);

    CtMethod[] methods = ctKlazz.getMethods();
    for (CtMethod method : methods) {
        final CtBehavior method = methods[ind];
        method.instrument(
            new ExprEditor() {
                // Instrument new expressions:
                public void edit(NewExpr expr) throws CannotCompileException {
                    final int allocSiteId = getAllocSiteId(className, expr.indexOfBytecode());
                    expr.replace( "{ $_ = $proceed($$); someCodeHere($_); }");
                }
            }
        );
        method.insertBefore("{ someInstrumentationAtStart(); }");
    }

    return ctKlazz;
}