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 .class0xCAFEBABECode
The JVM is a stack machine. Instructions take their operands from an operand stack and push results back: iload_1iaddireturnilfda
| Group | Examples | What they do |
|---|---|---|
| Loads and stores | iloadastorebipushldc | Move values between locals, constants and the stack |
| Arithmetic and conversion | iaddlmuli2l | Compute on the stack |
| Objects and arrays | newgetfieldarraylengthiaload | Create and access objects |
| Control flow | if_icmpgegotolookupswitchtableswitch | Branches and switches |
| Method calls | invokestaticinvokevirtualinvokeinterfaceinvokespecialinvokedynamic | Calls, with invokedynamic |
Tools for working with bytecode: javapjava.lang.instrumentjava.lang.classfile
Reading a class file header by hand
The first ten bytes of any class file can be read with a DataInputStreamString
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:
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
. 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, withCAFEBABE .UnsupportedClassVersionError - The constant pool of the small record already has 59 entries, because names, descriptors and the bootstrap method references for its generated
,toString andequals all live there.hashCode , with many methods, has 1,470.String - Bytecode in the constant pool is referenced by index:
in#7 output below means constant pool entry 7.javap
Disassembling methods with javap
javap -cjavapToolProvider
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:
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
}
is a literal translation: push the parameter (local 1, because local 0 isaddTen ), push the constant 10, add, store into local 2 (this ), load it again and return it.y does almost no optimization; the JIT compiler does that later, at run time.javac- The numbers on the left are byte offsets:
takes two bytes, so the next instruction is at 3.bipush 10 became a single"Hi " + name toinvokedynamic . Since Java 9 (JEP 280), the concatenation strategy is chosen by the JDK at run time rather than hard-coded asmakeConcatWithConstants calls in your class file; seeStringBuildermethod handles for how is linked.invokedynamic
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
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:
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
and does aString.hashCode on the hash, then confirms the match withlookupswitch , because different strings can share a hash. That sets an index, and a secondequals on the index jumps to the case body. Alookupswitch string fails at thenull call withhashCode .NullPointerException in a method returningreturn x; compiled toInteger : autoboxing is just a method call, which is why boxing in a hot loop costs allocations outside the small-value cache.Integer.valueOf- The enhanced
over an array became an index loop:for once, anarraylength test at the top, and aif_icmpge back. No iterator is involved; for angoto the compiler would callIterable ,iterator() andhasNext() instead, as thenext()Iterable page explains.
A Java agent that rewrites a class
A Java agent is a JAR whose manifest names a Premain-Class-javaagent:agent.jarpremain(String, Instrumentation)mainClassFileTransformerprintln
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:
[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
ran first and received the argument written after thepremain in= . The transformer was then offered every class that loaded; it returned-javaagent:...=verbose , meaning "unchanged", for all exceptnull .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 and the message.println andworkA printed the injected line when called;workB 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.helper gave 416 bytes forInstrumentation.getObjectSize : a 16-byte array header plus 100 × 4 bytes. A plainnew int[100] is 16 bytes. These are shallow sizes for this JVM's settings; seeObjectmemory 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 agentmainpremain-XX:+EnableDynamicAgentLoading-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
, which is how it can mock final classes. Unless Mockito is given asInstrumentation , 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.-javaagent - Hot reloading:
andInstrumentation.redefineClasses 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.retransformClasses - Size measurement:
is the only exact way to get an object's shallow size from Java code.getObjectSize
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
| Need | Use |
|---|---|
See what javac | javap -c -p-v |
| Generate or transform classes in new code (Java 24 and later) | The ClassFile API, java.lang.classfile |
| The same on older JDKs | ASM, or Byte Buddy for a higher-level API |
| Change classes of an application without touching its code | A Java agent with -javaagentClassFileTransformer |
| Measure the shallow size of objects | Instrumentation.getObjectSize |
| Define a generated class at run time | MethodHandles.Lookup.defineHiddenClass |
| Intercept calls on interfaces only | A |
See