-
I want to intercept a static method call in What am I missing to instrument a class of the bootstrap class loader?
public class Main {
//
// gw -p genthreadname/ clean shadowJar
// java -javaagent:genthreadname/build/libs/genthreadname.jar -jar genthreadname/build/libs/genthreadname.jar
//
public static void main(String[] args) throws Exception {
System.out.println("main.genThreadName() = " + genThreadName());
new Thread(() -> System.out.println("Thread.currentThread().getName() = " + Thread.currentThread().getName())).start();
}
static String genThreadName() {
return "test";
}
}
public class ThreadInstrumentationAgent {
public static void premain(@SuppressWarnings("unused") String agentArgs, Instrumentation inst) {
new AgentBuilder.Default()
.ignore(ElementMatchers.none())
.with(InitializationStrategy.NoOp.INSTANCE)
.with(RedefinitionStrategy.RETRANSFORMATION)
.with(RedefinitionStrategy.DiscoveryStrategy.Reiterating.INSTANCE)
.type((RawMatcher) (typeDescription, classLoader, module, classBeingRedefined, protectionDomain) -> {
String name = typeDescription.getName();
if ("java.lang.Thread".equals(name)) {
// if ("test.Main".equals(name)) { // works
return true;
}
return false;
})
.transform(new AgentBuilder.Transformer.ForAdvice()
.with(AgentBuilder.LocationStrategy.ForClassLoader.WEAK)
.include(Thread.class.getClassLoader())
.with(Assigner.DEFAULT)
.withExceptionHandler(new Advice.ExceptionHandler.Simple(Removal.SINGLE))
.advice(ElementMatchers.named("genThreadName"), ThreadGenThreadNameInterceptor.class.getName()))
.installOn(inst);
System.out.println("...premain done");
}
}
class ThreadGenThreadNameInterceptor {
@Advice.OnMethodExit
public static void enter(@Advice.Origin Method method) {
System.out.println(".intercepted " + method);
new RuntimeException().printStackTrace();
}
} |
Beta Was this translation helpful? Give feedback.
Answered by
raphw
Jun 6, 2025
Replies: 1 comment 3 replies
-
I get the following error when I enable logging with: .with(AgentBuilder.Listener.StreamWriting.toSystemError().withTransformationsOnly())
.with(AgentBuilder.InstallationListener.StreamWriting.toSystemError())
|
Beta Was this translation helpful? Give feedback.
3 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
When using
AgentBuilder.Transformer.ForAdvice()
, Byte Buddy will try to load the class file directly to render a description of the advice, without loading it. By usingAdvice.to(ThreadGenThreadNameInterceptor.class)
, the description is rendered using Java reflection.On this note,
.include(Thread.class.getClassLoader())
seems to be incorrect. Here you should include your agent's class loader that contains the advice classes. This is likely the real issue of your initial solution.