Byte Buddy Agent Builder
1. Basic Byte Buddy Agent
java Copy
import net.bytebuddy.agent.builder.AgentBuilder;
import net.bytebuddy.implementation.FixedValue;
import net.bytebuddy.matcher.ElementMatchers;
import java.lang.instrument.Instrumentation;
public class ByteBuddyAgent {
public static void premain (String args, Instrumentation inst) {
new AgentBuilder .Default()
.type(ElementMatchers.nameStartsWith("com.example.service." ))
.transform((builder, typeDescription, classLoader, module , domain) ->
builder.method(ElementMatchers.named("toString" ))
.intercept(FixedValue.value("Hello from ByteBuddy!" ))
)
.installOn(inst);
System.out.println("ByteBuddy agent installed" );
}
}2. Complete Timing Agent with Byte Buddy
java Copy
import net.bytebuddy.agent.builder.AgentBuilder;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.matcher.ElementMatchers;
import java.lang.instrument.Instrumentation;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
public class ByteBuddyTimingAgent {
private static final ConcurrentHashMap<String, AtomicLong> TIMINGS =
new ConcurrentHashMap <>();
public static void premain (String args, Instrumentation inst) {
new AgentBuilder .Default()
.type(ElementMatchers.nameStartsWith("com.example." ))
.transform(new AgentBuilder .Transformer.ForAdvice()
.advice(ElementMatchers.isMethod()
.and(ElementMatchers.not(ElementMatchers.isConstructor()))
.and(ElementMatchers.not(ElementMatchers.nameMatches("<.*>" ))),
TimingAdvice.class.getName()))
.installOn(inst);
}
public static class TimingAdvice {
@Advice .OnMethodEnter(suppress = Throwable.class)
public static long enter (@Advice .Origin Class<?> clazz) {
return System.nanoTime();
}
@Advice .OnMethodExit(suppress = Throwable.class, onThrowable = Throwable.class)
public static void exit (@Advice .Origin Class<?> clazz,
@Advice .Enter long startTime, @Advice .Thrown Throwable thrown) {
long elapsed = System.nanoTime() - startTime;
String key = clazz.getName() + "."
+ new Exception ().getStackTrace()[1 ].getMethodName();
TIMINGS.computeIfAbsent(key, k -> new AtomicLong ())
.addAndGet(elapsed);
}
}
}3. Advice Annotations Reference
java Copy
import net.bytebuddy.asm.Advice;
public class AdviceExamples {
@Advice .OnMethodEnter(suppress = Throwable.class)
public static void onEnter (
@Advice .Origin Class<?> clazz,
@Advice .Origin Method method,
@Advice .AllArguments Object[] args,
@Advice .Argument(0 ) Object firstArg,
@Advice .Local("myVar" ) Object localVar) {
}
@Advice .OnMethodExit(onThrowable = Throwable.class)
public static void onExit (
@Advice .Return Object returnValue,
@Advice .Thrown Throwable thrown,
@Advice .Local("myVar" ) Object localVar) {
}
}4. Method Delegation
java Copy
import net.bytebuddy.implementation.MethodDelegation;
public static void premain (String args, Instrumentation inst) {
new AgentBuilder .Default()
.type(ElementMatchers.nameStartsWith("com.example." ))
.transform((builder, type, cl, module , pd) ->
builder.method(ElementMatchers.named("process" ))
.intercept(MethodDelegation.to(Interceptor.class))
)
.installOn(inst);
}
public static class Interceptor {
@RuntimeType
public static Object intercept (
@Origin Method method,
@AllArguments Object[] args,
@SuperCall Callable<?> callable) throws Exception {
System.out.println("Before: " + method.getName());
try { return callable.call(); }
finally { System.out.println("After: " + method.getName()); }
}
}
java Copy
import net.bytebuddy.agent.builder.AgentBuilder;
public class TransformListener implements AgentBuilder .Listener {
@Override
public void onTransformation (TypeDescription typeDescription,
ClassLoader classLoader, JavaModule module ,
boolean loaded, DynamicType dynamicType) {
System.out.println("Transformed: " + typeDescription.getName());
}
@Override
public void onError (String typeName, ClassLoader classLoader,
JavaModule module , boolean loaded, Throwable throwable) {
System.err.println("Error transforming " + typeName + ": " + throwable);
}
@Override
public void onDiscovery (String typeName, ClassLoader classLoader,
JavaModule module , boolean loaded) { }
@Override
public void onIgnored (TypeDescription typeDescription,
ClassLoader classLoader, JavaModule module , boolean loaded) { }
@Override
public void onComplete (String typeName, ClassLoader classLoader,
JavaModule module , boolean loaded) { }
}6. Comparison: Byte Buddy vs Raw ASM
Byte Buddy advantages:
Type-safe advice annotations (no manual bytecode for entry/exit)
Automatic stack frame computation
Method delegation support
Better error messages and debugging
ASM is lower-level and more efficient for simple transformations.
Key points: Byte Buddy's AgentBuilder provides a high-level API for class transformation, Advice annotations handle entry/exit instrumentation, and method delegation allows intercepting calls to other methods.