Search code examples
javabyte-buddyjavaagents

How to pass variables to advice?


I'd like to pass the "agentArgs" parameter of a javagent to my advice. How could I achieve that?

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???
    }
}

Working solution suggested by @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);
    }
}

Solution

  • You can provide compile-time constants (such as strings) to an advice by binding a custom annotation to an argument:

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

    Make sure that the annotation is retained at runtime, otherwise Byte Buddy cannot discover it.