How to Dynamically Change Java Object Behavior with Instrumentation, BTrace, and Arthas

This article explains how Java object behavior is stored in the JVM method area, how to use java.lang.instrument.Instrumentation, direct bytecode manipulation, BTrace, and Arthas to modify methods at runtime without changing object state, and provides practical code examples and tool architectures.

Java Interview Crash Guide
Java Interview Crash Guide
Java Interview Crash Guide
How to Dynamically Change Java Object Behavior with Instrumentation, BTrace, and Arthas

Java Object Behavior

The problem described at the beginning is essentially about dynamically changing the behavior of already‑existing objects in memory. To solve it we first need to understand where the JVM stores information related to object behavior and whether it can be altered.

In Java, an object consists of two parts: attributes (state) and behaviors (methods). Attributes are stored per‑instance, while behaviors are shared among all instances of a class.

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;
    }
}

Person personA = new Person(43, "lixunhuan");
personA.speak("我是李寻欢");
Person personB = new Person(23, "afei");
personB.speak("我是阿飞");

When two Person objects are created, they each have their own age and name, but they share the same speak method. The JVM stores these shared methods in the Method Area , which is created at virtual‑machine startup and is part of the heap.

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.

Method‑area data originates from class files, which are produced by compiling Java (or any JVM‑language) source code. To modify a method at runtime we can replace the class definition using java.lang.instrument.Instrumentation:

Instrumentation API

The API provides two key methods: redefineClasses – replace a class with a new byte‑code definition. retransformClasses – transform existing byte‑code and then replace it.

Both operations have strict limitations (no adding/removing fields or methods, no changing signatures, etc.) to keep the JVM safe.

Direct Bytecode Manipulation

Instead of writing Java source again, we can edit the bytecode directly. The most popular library for this is ASM , which underlies frameworks such as cglib, Spring AOP, and many other bytecode‑generation tools.

BTrace

BTrace is an open‑source, safe dynamic tracing tool built on ASM, the Java Attach API, and Instrumentation. It lets you write simple Java‑style scripts that are compiled to bytecode and injected into a running JVM without writing raw ASM code.

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);
    }
}

BTrace also supports timers, counters, and other utilities, as shown in the following example that prints the number of created threads every two seconds:

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: the script, a compiler that turns the script into a class file, a client that sends the class to an agent, and the agent (using Attach API) that loads the class, rewrites bytecode, and invokes retransformClasses.

Arthas

Arthas is an Alibaba‑open‑source Java diagnostic tool that wraps the same underlying technologies (Instrumentation, Attach API, ASM) and provides a user‑friendly command‑line interface for dynamic tracing, monitoring, and troubleshooting.

In summary, by understanding the JVM method area, using the Instrumentation API, and leveraging tools such as ASM, BTrace, and Arthas, developers can modify method behavior at runtime, add logging, or perform sophisticated diagnostics without altering source code or restarting the application.

BTrace architecture diagram
BTrace architecture diagram
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Instrumentationbytecodedynamic tracingBTrace
Java Interview Crash Guide
Written by

Java Interview Crash Guide

Dedicated to sharing Java interview Q&A; follow and reply "java" to receive a free premium Java interview guide.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.