Как получить аргумент из метода premain в @ Advice.OnMethodExit? - PullRequest
0 голосов
/ 16 апреля 2020
public static void premain(String arg, Instrumentation instrumentation) {
        System.out.println("Agent for time measure:" + arg);
}

Я хочу получить аргумент по методу ниже, иначе аргумент не используется. Лучше всего, в методе OnMethodExit получить arg.

public class TimerAdvice3 {

    @Advice.OnMethodEnter
    static long enter(@Advice.Origin String method, @Advice.AllArguments Object[] args) throws Exception {
        HttpUriRequest httpUriRequest = (HttpUriRequest) args[1];
        System.out.println(httpUriRequest.toString());
        long start = System.currentTimeMillis();
        return start;
    }

    @Advice.OnMethodExit
    static void exit(@Advice.Origin String method, @Advice.Enter long start) throws Exception {
        long end = System.currentTimeMillis();
        System.out.println("拦截======》" + method + " took " + (end - start) + " milliseconds ");
    }

}

Ответы [ 2 ]

0 голосов
/ 16 апреля 2020
public static void premain(String arg, Instrumentation instrumentation) {
        System.out.println("Agent for time measure:" + arg);

        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter("./premain-arg");
            fileWriter.append(arg);
            fileWriter.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileWriter != null) {
                try {
                    fileWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

это мое решение , но я не думаю, что оно идеально

0 голосов
/ 16 апреля 2020

Вы пытаетесь применить совет, который вы написали? Для этого вам нужно использовать AgentBuilder API:

new AgentBuilder.Default()
  .type(...)
  .transform((builder, type, classLoader, module) -> builder.visit(Advice
     .withCustomConfiguration()
     .bind(MyAnnotation.class, arg)
     .to(TimerAdvice.class)
     .on(...))
  .installOn(instrumentation);

Теперь вы можете использовать:

static long enter(@Advice.Origin String method, 
    @Advice.AllArguments Object[] args, 
    @MyAnnotation String arg) { ... }

Вы также можете использовать @Advice.Argument(0), если хотите только чтение HttpUriRequest. Просто убедитесь, что вы используете RetentionPolicy.RUNTIME.

...