Bytecode and instrumentation

javac turns Java source into bytecode, a compact instruction set for a stack machine, and the JVM runs that. Reading bytecode explains many language behaviours, and a Java agent can inspect or rewrite it as classes load. This page explains the class file format, reads a class file header by hand, disassembles real methods, shows what javac generates for common constructs, and builds a Java agent that rewrites methods with the ClassFile API from Java 24.

Contents

What is in a class file

Every .class file has the same layout, defined in chapter 4 of the JVM specification: the magic number 0xCAFEBABE, a minor and major version, a constant pool holding every name, string, number and method reference the class uses, then the class's flags, superclass, interfaces, fields and methods. Each method body is a Code attribute: a byte array of instructions plus the maximum stack depth, the number of local variables, an exception table and, since Java 7's verifier, stack map frames that describe the types at branch targets.

The JVM is a stack machine. Instructions take their operands from an operand stack and push results back: iload_1 pushes local variable 1, iadd pops two ints and pushes their sum, ireturn returns the int on top. The prefix gives the type: i for int, l long, f float, d double, a reference. There are about 200 opcodes, grouped roughly as follows.

Groups of JVM instructions
GroupExamplesWhat they do
Loads and storesiload, astore, bipush, ldcMove values between locals, constants and the stack
Arithmetic and conversioniadd, lmul, i2lCompute on the stack
Objects and arraysnew, getfield, arraylength, ialoadCreate and access objects
Control flowif_icmpge, goto, lookupswitch, tableswitchBranches and switches
Method callsinvokestatic, invokevirtual, invokeinterface, invokespecial, invokedynamic (Java 7)Calls, with invokedynamic linked at run time

Tools for working with bytecode: javap in the JDK to read it; java.lang.instrument (Java 5) to change classes as they load; and, for generating or transforming bytecode, the libraries ASM and Byte Buddy or the JDK's own ClassFile API (java.lang.classfile), a preview in Java 22 and final in Java 24 (JEP 484). Because the last example uses that API, this page was compiled and run on JDK 25; the class file versions below are therefore 69.

Reading a class file header by hand

The first ten bytes of any class file can be read with a DataInputStream. The program reads them for its own class, a record and String, three classes of very different size.

Java
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;

public class ClassFileHeader {

    record Point(int x, int y) { }

    public static void main(String[] args) throws IOException {
        for (Class<?> c : new Class<?>[] {ClassFileHeader.class, Point.class, String.class}) {
            String resource = "/" + c.getName().replace('.', '/') + ".class";
            try (InputStream raw = c.getResourceAsStream(resource);
                 DataInputStream in = new DataInputStream(raw)) {
                int magic = in.readInt();               // always 0xCAFEBABE
                int minor = in.readUnsignedShort();
                int major = in.readUnsignedShort();     // 65 = Java 21, 69 = Java 25
                int poolCount = in.readUnsignedShort(); // constant pool entries + 1
                System.out.printf("%-24s magic %X, version %d.%d (Java %d), "
                                + "constant pool %d entries%n",
                        c.getSimpleName(), magic, major, minor, major - 44, poolCount - 1);
            }
        }
    }
}

Output:

Output
ClassFileHeader          magic CAFEBABE, version 69.0 (Java 25), constant pool 108 entries
Point                    magic CAFEBABE, version 69.0 (Java 25), constant pool 59 entries
String                   magic CAFEBABE, version 69.0 (Java 25), constant pool 1470 entries
  • All three start with CAFEBABE. The major version 69 means Java 25: the number is the Java version plus 44, so Java 8 is 52, Java 17 is 61 and Java 21 is 65. A JVM refuses class files with a higher major version than it supports, with UnsupportedClassVersionError.
  • The constant pool of the small record already has 59 entries, because names, descriptors and the bootstrap method references for its generated toString, equals and hashCode all live there. String, with many methods, has 1,470.
  • Bytecode in the constant pool is referenced by index: #7 in javap output below means constant pool entry 7.

Disassembling methods with javap

javap -c prints the bytecode of each method. The program runs the JDK's javap in-process through ToolProvider and prints two small methods: one with arithmetic and one with string concatenation.

Java
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.spi.ToolProvider;

public class Javap {

    // The class we will disassemble
    static class Calc {
        int addTen(int x) {
            int y = x + 10;
            return y;
        }

        String greet(String name) {
            return "Hi " + name;
        }
    }

    public static void main(String[] args) {
        // Run the JDK's javap tool in-process, exactly as 'javap -c' on the command line
        ToolProvider javap = ToolProvider.findFirst("javap").orElseThrow();
        StringWriter out = new StringWriter();
        String classPath = System.getProperty("java.class.path");
        javap.run(new PrintWriter(out), new PrintWriter(out), "-c", "-cp", classPath, "Javap$Calc");

        // Print only the two methods we care about
        boolean show = false;
        for (String line : out.toString().split("\n")) {
            if (line.contains("addTen(int)") || line.contains("greet(java.lang.String)")) {
                show = true;
            }
            if (show) {
                System.out.println(line);
            }
            if (show && line.isBlank()) {
                show = false;
            }
        }
    }
}

Output:

Output
int addTen(int);
    Code:
         0: iload_1
         1: bipush        10
         3: iadd
         4: istore_2
         5: iload_2
         6: ireturn

  java.lang.String greet(java.lang.String);
    Code:
         0: aload_1
         1: invokedynamic #7,  0              // InvokeDynamic #0:makeConcatWithConstants:(Ljava/lang/String;)Ljava/lang/String;
         6: areturn
}
  • addTen is a literal translation: push the parameter (local 1, because local 0 is this), push the constant 10, add, store into local 2 (y), load it again and return it. javac does almost no optimization; the JIT compiler does that later, at run time.
  • The numbers on the left are byte offsets: bipush 10 takes two bytes, so the next instruction is at 3.
  • "Hi " + name became a single invokedynamic to makeConcatWithConstants. Since Java 9 (JEP 280), the concatenation strategy is chosen by the JDK at run time rather than hard-coded as StringBuilder calls in your class file; see method handles for how invokedynamic is linked.

What javac generates for common constructs

Several language features are compiled into ordinary method calls and branches. The program disassembles a string switch, an autoboxed return and an enhanced for loop over an array, and prints only the instructions that reveal the translation.

Java
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.List;
import java.util.spi.ToolProvider;

public class JavacTricks {

    static class Samples {
        int day(String name) {
            switch (name) {                       // a switch on strings
                case "mon":
                    return 1;
                case "tue":
                    return 2;
                default:
                    return 0;
            }
        }

        Integer boxed(int x) {
            return x;                             // autoboxing
        }

        int sum(int[] values) {
            int total = 0;
            for (int v : values) {                // enhanced for over an array
                total += v;
            }
            return total;
        }
    }

    public static void main(String[] args) {
        ToolProvider javap = ToolProvider.findFirst("javap").orElseThrow();
        StringWriter out = new StringWriter();
        javap.run(new PrintWriter(out), new PrintWriter(out), "-c",
                "-cp", System.getProperty("java.class.path"), "JavacTricks$Samples");
        String text = out.toString();

        // Show only the instructions that reveal what javac generated
        for (String method : List.of("int day(", "java.lang.Integer boxed(", "int sum(")) {
            System.out.println(method.trim() + "...)");
            String body = text.substring(text.indexOf(method));
            int end = body.indexOf("\n\n");
            body = end > 0 ? body.substring(0, end) : body;
            for (String line : body.split("\n")) {
                if (line.contains("invoke") || line.contains("switch")
                        || line.contains("arraylength") || line.contains("if_icmpge")
                        || line.contains("goto")) {
                    System.out.println("  " + line.trim().replaceAll("\\s+", " "));
                }
            }
        }
    }
}

Output:

Output
int day(...)
  5: invokevirtual #7 // Method java/lang/String.hashCode:()I
  8: lookupswitch { // 2
  39: invokevirtual #15 // Method java/lang/String.equals:(Ljava/lang/Object;)Z
  47: goto 61
  53: invokevirtual #15 // Method java/lang/String.equals:(Ljava/lang/Object;)Z
  62: lookupswitch { // 2
java.lang.Integer boxed(...)
  1: invokestatic #21 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
int sum(...)
  5: arraylength
  15: if_icmpge 35
  32: goto 11
  • A switch on strings is two switches. The first calls String.hashCode and does a lookupswitch on the hash, then confirms the match with equals, because different strings can share a hash. That sets an index, and a second lookupswitch on the index jumps to the case body. A null string fails at the hashCode call with NullPointerException.
  • return x; in a method returning Integer compiled to Integer.valueOf: autoboxing is just a method call, which is why boxing in a hot loop costs allocations outside the small-value cache.
  • The enhanced for over an array became an index loop: arraylength once, an if_icmpge test at the top, and a goto back. No iterator is involved; for an Iterable the compiler would call iterator(), hasNext() and next() instead, as the Iterable page explains.

A Java agent that rewrites a class

A Java agent is a JAR whose manifest names a Premain-Class. When the JVM is started with -javaagent:agent.jar, it calls that class's premain(String, Instrumentation) before the application's main. The agent can register a ClassFileTransformer, which receives the bytes of every class as it loads and may return different bytes. The program builds an agent JAR, starts a second JVM with it, and the agent uses the ClassFile API to insert a println at the start of every method whose name begins with "work".

Java
import java.io.IOException;
import java.lang.classfile.ClassFile;
import java.lang.classfile.ClassTransform;
import java.lang.classfile.CodeBuilder;
import java.lang.classfile.CodeElement;
import java.lang.classfile.CodeTransform;
import java.lang.constant.ClassDesc;
import java.lang.constant.ConstantDescs;
import java.lang.constant.MethodTypeDesc;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.Instrumentation;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.ProtectionDomain;
import java.util.jar.Attributes;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;

public class AgentDemo {

    // ---- The agent: the JVM calls premain before the application's main ----
    public static class Agent {
        static Instrumentation inst;

        public static void premain(String agentArgs, Instrumentation instrumentation) {
            System.out.println("[agent] premain called, args=" + agentArgs);
            inst = instrumentation;
            instrumentation.addTransformer(new ClassFileTransformer() {
                @Override
                public byte[] transform(Module module, ClassLoader loader, String className,
                        Class<?> redefined, ProtectionDomain domain, byte[] bytes) {
                    if (!"AgentDemo$App".equals(className)) {
                        return null;                       // null = leave the class unchanged
                    }
                    byte[] changed = addEntryLog(bytes);
                    System.out.println("[agent] rewrote " + className + ": " + bytes.length
                            + " -> " + changed.length + " bytes");
                    return changed;
                }
            });
        }

        // ClassFile API (final in Java 24): insert a println at the start of every "work*"
        static byte[] addEntryLog(byte[] bytes) {
            ClassFile cf = ClassFile.of();
            ClassDesc system = ClassDesc.of("java.lang.System");
            ClassDesc printStream = ClassDesc.of("java.io.PrintStream");
            return cf.transformClass(cf.parse(bytes), ClassTransform.transformingMethodBodies(
                    m -> m.methodName().stringValue().startsWith("work"),
                    new CodeTransform() {
                        @Override
                        public void atStart(CodeBuilder b) {
                            b.getstatic(system, "out", printStream)
                                    .ldc("[injected] entering a work method")
                                    .invokevirtual(printStream, "println",
                                            MethodTypeDesc.of(ConstantDescs.CD_void,
                                                    ConstantDescs.CD_String));
                        }

                        @Override
                        public void accept(CodeBuilder b, CodeElement e) {
                            b.with(e);                     // keep every original instruction
                        }
                    }));
        }
    }

    // ---- The application the agent rewrites ----
    public static class App {
        static int workA(int x) {
            return x * 2;
        }

        static int workB(int x) {
            return x + 1;
        }

        static int helper(int x) {
            return x;
        }

        public static void main(String[] args) {
            System.out.println("[app] main running");
            System.out.println("[app] workA(20) = " + workA(20));
            System.out.println("[app] workB(20) = " + workB(20));
            System.out.println("[app] helper(20) = " + helper(20));
            System.out.println("[app] size of new int[100]: "
                    + Agent.inst.getObjectSize(new int[100]) + " bytes");
            System.out.println("[app] size of new Object(): "
                    + Agent.inst.getObjectSize(new Object()) + " bytes");
        }
    }

    // ---- Driver: build an agent jar, then start a JVM that uses it ----
    public static void main(String[] args) throws IOException, InterruptedException {
        Path jar = Files.createTempFile("agent", ".jar");
        Manifest mf = new Manifest();
        mf.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
        mf.getMainAttributes().putValue("Premain-Class", "AgentDemo$Agent");
        try (JarOutputStream out = new JarOutputStream(Files.newOutputStream(jar), mf)) {
            out.putNextEntry(new JarEntry("placeholder.txt"));   // classes come from -cp
            out.closeEntry();
        }

        String java = Path.of(System.getProperty("java.home"), "bin", "java").toString();
        Process p = new ProcessBuilder(java, "-javaagent:" + jar + "=verbose",
                "-cp", System.getProperty("java.class.path"), "AgentDemo$App")
                .redirectErrorStream(true).start();
        p.getOutputStream().close();                      // the child reads no input
        p.getInputStream().transferTo(System.out);
        System.out.println("child JVM exit code: " + p.waitFor());
        Files.delete(jar);
    }
}

Output:

Output
[agent] premain called, args=verbose
[agent] rewrote AgentDemo$App: 1642 -> 1697 bytes
[app] main running
[injected] entering a work method
[app] workA(20) = 40
[injected] entering a work method
[app] workB(20) = 21
[app] helper(20) = 20
[app] size of new int[100]: 416 bytes
[app] size of new Object(): 16 bytes
child JVM exit code: 0
  • premain ran first and received the argument written after the = in -javaagent:...=verbose. The transformer was then offered every class that loaded; it returned null, meaning "unchanged", for all except AgentDemo$App.
  • The rewritten class grew from 1,642 to 1,697 bytes: three instructions per method, plus new constant pool entries for System.out, println and the message. workA and workB printed the injected line when called; helper did not match the name filter and was left alone. The ClassFile API recomputed the stack maps, a step that hand-written bytecode tools often get wrong.
  • Instrumentation.getObjectSize gave 416 bytes for new int[100]: a 16-byte array header plus 100 × 4 bytes. A plain Object is 16 bytes. These are shallow sizes for this JVM's settings; see memory management for object layout.
  • The transformer must never throw: an exception is silently ignored and the class loads unchanged. Agents also see their own classes and the JDK's, so filter on the class name, as here.

Agents can also be loaded into a running JVM through the attach API, calling agentmain instead of premain. Since Java 21 (JEP 451) that prints a warning unless the JVM was started with -XX:+EnableDynamicAgentLoading, and a future release is expected to disallow it by default; tools such as profilers and APM agents should be started with -javaagent.

What agents are used for, and their limits

  • Monitoring and tracing: APM agents (OpenTelemetry, commercial APMs) add timing around methods of known libraries, such as JDBC drivers and HTTP clients, without code changes.
  • Testing and mocking: in current Mockito releases (5.17 was tested here), the default "inline" mock maker rewrites the mocked classes themselves through Instrumentation, which is how it can mock final classes. Unless Mockito is given as -javaagent, it attaches the Byte Buddy agent to the running JVM; on JDK 21, mocking a final class with Mockito 5.17 printed "Mockito is currently self-attaching to enable the inline-mock-maker" followed by the JEP 451 warning "A Java agent has been loaded dynamically". Coverage tools such as JaCoCo also run as agents and add counters to every branch.
  • Hot reloading: Instrumentation.redefineClasses and retransformClasses replace method bodies in loaded classes. They may not add or remove fields or methods, change signatures or change the superclass, which limits what IDE "hot swap" can do.
  • Size measurement: getObjectSize is the only exact way to get an object's shallow size from Java code.

Agents run with full access to the application and to every class it loads, so only use agents you trust, and keep transformers fast, since they run for every class load.

Choosing a bytecode tool

Tools for reading and changing bytecode
NeedUse
See what javac producedjavap -c -p, with -v for the constant pool
Generate or transform classes in new code (Java 24 and later)The ClassFile API, java.lang.classfile
The same on older JDKsASM, or Byte Buddy for a higher-level API
Change classes of an application without touching its codeA Java agent with -javaagent and a ClassFileTransformer
Measure the shallow size of objectsInstrumentation.getObjectSize from an agent
Define a generated class at run timeMethodHandles.Lookup.defineHiddenClass
Intercept calls on interfaces onlyA dynamic proxy, no bytecode needed

See class loading for when transformers run, and async-profiler for a profiler that attaches as an agent.