简体   繁体   English

使用不带 -javaagent 参数的 ByteBuddy Java 代理

[英]Using ByteBuddy Java agent without -javaagent argument

I am trying to instrument some classes in a project.我正在尝试在项目中检测一些类。 When I package the agent classes into a jar and use it via -javaagent it works fine.当我将 package 代理类放入 jar 并通过 -javaagent 使用它时,它工作正常。

public static void premain(String arguments, Instrumentation instrumentation) {

        new AgentBuilder.Default()
                .type(ElementMatchers.nameStartsWith("com.cn."))
                .transform((builder, type, cl, m) -> builder
                        .method(ElementMatchers.isAnnotatedWith(Retryable.class))
                        .intercept(to(Retry.class)))
                .installOn(instrumentation);
    }

When I try to run it directly in the project the instrumentation fails sometimes.当我尝试直接在项目中运行它时,检测有时会失败。 (I initialize bytebuddy in a static block of the test class). (我在测试类的 static 块中初始化 bytebuddy)。

    static {
        Instrumentation inst = ByteBuddyAgent.install();

        new AgentBuilder.Default()
                .type(ElementMatchers.nameStartsWith("com.cn."))
                .transform((builder, type, cl, m) -> builder
                        .method(ElementMatchers.isAnnotatedWith(Retryable.class))
                        .intercept(to(Retry.class)))
                .installOn(inst);
    }

For instance when I add this test, my code is no longer intercepted.例如,当我添加此测试时,我的代码不再被拦截。 Doing the same with try/catch works.对 try/catch 做同样的事情。

RuntimeException e = Assertions.assertThrows(RuntimeException.class, () -> f.doit("doit foo"));

Is there a safe way to instrument classes in the same project without -javaagent?有没有一种安全的方法可以在没有-javaagent 的情况下在同一个项目中检测类?

Project is on OpenJdk11.项目在 OpenJdk11 上。

Using the -javaagent option you'll always be sure that your classes are loaded after the agent has been installed.使用 -javaagent 选项,您将始终确保在安装代理后加载您的类。

If you install the agent in a static block you have to assure that this piece of code is executed before any classes you want to instrument are loaded.如果将代理安装在 static 块中,则必须确保在加载要检测的任何类之前执行这段代码。 Eg.例如。 you could install the agent in your main method or in a static block where the main method resides as well.您可以将代理安装在您的主要方法中,或者安装在主要方法所在的 static 块中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM