如何将变量传递给建议?

How to pass variables to advice?

我想将 javagent 的“agentArgs”参数传递给我的建议。我怎样才能做到这一点?

public static void premain(String agentArgs, Instrumentation inst) {
    new AgentBuilder.Default()
            .type(named("org.some.class"))
            .transform((builder, type, classLoader, module) ->
                    builder.method(named("myMethod"))
                            .intercept(Advice.to(MyAdvice.class))
            ).installOn(inst);
}

public static class MyAdvice {
    @Advice.OnMethodEnter
    public static void myMethod(@Advice.AllArguments Object[] args) {
        // agentArgs???
    }
}

@Rafael Winterhalter 建议的工作解决方案:

public static void premain(String agentArgs, Instrumentation inst) {
    new AgentBuilder.Default()
            .type(named("org.some.class"))
            .transform((builder, type, classLoader, module) ->
                    builder.method(named("myMethod"))
                            .intercept(Advice.withCustomMapping().bind(AgentArguments.class, agentArgs).to(MyAdvice.class))
            ).installOn(inst);
}

// New annotation to pass the variable
@Retention(RetentionPolicy.RUNTIME)
public @interface AgentArguments {
}

public static class MyAdvice {
    // I can read the variable by adding it to the method signature
    @Advice.OnMethodEnter
    public static void myMethod(@Advice.AllArguments Object[] args, @AgentArguments String agentArguments) {
        System.out.println(agentArguments);
    }
}

您可以通过将自定义注释绑定到参数来为建议提供编译时常量(例如字符串):

Advice.withCustomBinding().bind(MyAnnotation.class, myString).to(MyAdvice.class)

确保运行时保留注解,否则字节好友无法发现。