How to Dynamically Modify Java Object Behavior with Instrumentation, BTrace, and Arthas
This article explains how Java object behavior is stored in the JVM method area, explores the java.lang.instrument.Instrumentation API for redefining and retransformation of classes, and demonstrates practical dynamic tracing and bytecode manipulation using tools like ASM, BTrace, and Arthas to inject logging and diagnostics at runtime.
Java Object Behavior
The initial problem is about dynamically changing the behavior of already‑existing objects in memory, which requires understanding where the JVM stores object behavior and whether it can be altered.
public class Person {
private int age;
private String name;
public void speak(String str) {
System.out.println(str);
}
public Person(int age, String name) {
this.age = age;
this.name = name;
}
}Instances personA and personB share the speak method while having separate fields, illustrating that method code is common to all objects.
Method Area
Method area is created on virtual machine startup, shared among all Java virtual machine threads and it is logically part of heap area. It stores per‑class structures such as the run‑time constant pool, field and method data, and the code for methods and constructors.
Java stores object behavior (methods) in the method area.
java.lang.instrument.Instrumentation
The Instrumentation API provides two key methods: redefineClasses to replace a class definition with new bytecode, and retransformClasses to modify existing bytecode before reloading.
The redefinition may change method bodies, the constant pool and attributes. The redefinition must not add, remove or rename fields or methods, change the signatures of methods, or change inheritance. ... If the resultant bytes are in error this method will throw an exception.
These operations enable adding logging or other simple behavior changes without altering object fields.
Direct Bytecode Manipulation
Frameworks like ASM allow developers to edit class bytecode directly, creating or modifying classes at runtime. Spring AOP, for example, uses ASM to generate proxy classes on the fly.
BTrace
BTrace is a safe, dynamic tracing tool for the Java platform that leverages ASM, the Attach API, and Instrumentation to inject tracing code without writing low‑level bytecode.
package com.sun.btrace.samples;
import com.sun.btrace.annotations.*;
import com.sun.btrace.AnyType;
import static com.sun.btrace.BTraceUtils.*;
@BTrace
public class ArgArray {
@OnMethod(clazz="/java\\.io\\..*/", method="/read.*/")
public static void anyRead(@ProbeClassName String pcn, @ProbeMethodName String pmn, AnyType[] args) {
println(pcn);
println(pmn);
printArray(args);
}
}Another example counts thread creations:
package com.sun.btrace.samples;
import com.sun.btrace.annotations.*;
import static com.sun.btrace.BTraceUtils.*;
@BTrace
public class ThreadCounter {
@Export
private static long count;
@OnMethod(clazz="java.lang.Thread", method="start")
public static void onnewThread(@Self Thread t) {
count++;
}
@OnTimer(2000)
public static void ontimer() {
println(count);
}
}BTrace’s architecture consists of four modules: Script, Compiler, Client, and Agent. The Agent attaches to a running JVM via the Attach API, receives compiled BTrace classes, rewrites bytecode, and invokes Instrumentation’s retransform interface.
Script – user‑written BTrace code with annotations.
Compiler – compiles scripts to class files.
Client – sends class files to the Agent.
Agent – attaches to the target JVM, modifies bytecode, and applies changes.
Below is a simplified workflow diagram:
Arthas
Arthas is an open‑source Java diagnostic tool from Alibaba that provides simple command‑line operations for dynamic tracing, building on the same Instrumentation and Attach API principles.
After understanding the underlying mechanisms, developers can create their own tracing solutions or use existing tools like BTrace and Arthas to efficiently locate and diagnose runtime issues.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Backend Technology
Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
