简体   繁体   中英

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.

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 {
        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.

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

Is there a safe way to instrument classes in the same project without -javaagent?

Project is on OpenJdk11.

Using the -javaagent option you'll always be sure that your classes are loaded after the agent has been installed.

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. Eg. you could install the agent in your main method or in a static block where the main method resides as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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