Java Bytecode Engineering: Modifying Class Files with ASM and Java Agents
Process annotations at the bytecode level: the class file format, javap, CLASS-retention annotations, inserting logging code with ASM's AdviceAdapter, the new Class-File API, and rewriting classes at load time with a Java agent and ClassFileTransformer.
kvi5hnuCode Sprout team member9 min readOn this page
You've now seen annotations processed at runtime with reflection (article 108) and at the source level with annotation processors (article 109). There's a third place: the bytecode. Unless an annotation has SOURCE retention, it's stored in the class file, and a tool can read the class file, find the annotation, and change the virtual machine instructions. Code coverage tools such as JaCoCo, profilers and APM agents, mocking libraries such as Mockito, and frameworks such as Hibernate and Spring all do this behind the scenes.
The class file format
The format of .class files is documented in chapter 4 of the Java Virtual Machine Specification. In outline, a class file contains:
- the magic number
0xCAFEBABEand the minor and major version. Major 52 is Java 8, 61 is Java 17, 65 is Java 21, and in general major − 44 is the Java version. - the constant pool: every string literal, class name, method name, descriptor and numeric constant the class uses, referenced from elsewhere by index
- access flags, this class, the superclass and interfaces
- fields and methods, each with attributes. The
Codeattribute holds a method's bytecodes, andRuntimeVisibleAnnotationsandRuntimeInvisibleAnnotationshold its annotations (RUNTIMEandCLASSretention respectively).
The JDK's javap shows a class file's contents. javap -c disassembles the bytecodes, javap -v shows everything including the constant pool, and javap -p includes private members.
The format is detailed, and writing to it by hand is error-prone. Bytecode tools therefore use a library. The classic one is ASM (asm.ow2.org, currently version 9.x). Since Java 24, the JDK includes its own Class-File API, java.lang.classfile (JEP 484), which always supports the newest class file version.
Example: inserting log statements with ASM
Suppose we want to log an entry message for selected methods. Mark them with an annotation of CLASS retention. It doesn't need to be visible at runtime, only in the class file:
@Retention(RetentionPolicy.CLASS)
@Target(ElementType.METHOD)
public @interface LogEntry { String logger(); }
For a method annotated with
@LogEntry(logger = "com.example") public int hashCode() { ... }
the tool inserts the bytecodes of this statement at the start of the method:
System.getLogger("com.example").log(System.Logger.Level.INFO,
"Entering {0}.{1}", className, methodName);
Then each call prints a message like INFO: Entering set.Item.hashCode. The steps are:
- Load the bytecodes of the class file.
- Visit all methods.
- For each method, check whether it has a
@LogEntryannotation. - If it does, insert these instructions at the start of the method:
ldc "com.example"
invokestatic System.getLogger(String)
getstatic System.Logger.Level.INFO
ldc "Entering {0}.{1}"
iconst_2
anewarray Object
dup
iconst_0
ldc "set.Item"
aastore
dup
iconst_1
ldc "hashCode"
aastore
invokeinterface System.Logger.log(Level, String, Object[])
ASM is built around the visitor pattern. A ClassReader walks the class file and calls methods on a ClassVisitor chain, which ends in a ClassWriter that produces new bytes. To modify something, you put a visitor in the middle. AdviceAdapter from asm-commons gives you an onMethodEnter hook. Method annotations are visited before the code, so we can record the logger name first and use it when the method body starts:
import java.io.*;
import java.nio.file.*;
import org.objectweb.asm.*;
import org.objectweb.asm.commons.*;
public class EntryLogger extends ClassVisitor {
private final String className;
public EntryLogger(ClassVisitor next, String className) {
super(Opcodes.ASM9, next);
this.className = className;
}
@Override
public MethodVisitor visitMethod(int access, String name, String desc,
String signature, String[] exceptions) {
MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions);
return new AdviceAdapter(Opcodes.ASM9, mv, access, name, desc) {
private String loggerName;
@Override
public AnnotationVisitor visitAnnotation(String annDesc, boolean visible) {
AnnotationVisitor av = super.visitAnnotation(annDesc, visible);
if (!annDesc.equals("Lbytecode/LogEntry;")) return av;
return new AnnotationVisitor(Opcodes.ASM9, av) {
@Override public void visit(String element, Object value) {
if (element.equals("logger")) loggerName = (String) value;
super.visit(element, value);
}
};
}
@Override
protected void onMethodEnter() {
if (loggerName == null) return; // method not annotated
visitLdcInsn(loggerName);
visitMethodInsn(INVOKESTATIC, "java/lang/System", "getLogger",
"(Ljava/lang/String;)Ljava/lang/System$Logger;", false);
visitFieldInsn(GETSTATIC, "java/lang/System$Logger$Level", "INFO",
"Ljava/lang/System$Logger$Level;");
visitLdcInsn("Entering {0}.{1}");
visitInsn(ICONST_2);
visitTypeInsn(ANEWARRAY, "java/lang/Object");
visitInsn(DUP); visitInsn(ICONST_0); visitLdcInsn(className); visitInsn(AASTORE);
visitInsn(DUP); visitInsn(ICONST_1); visitLdcInsn(getName()); visitInsn(AASTORE);
visitMethodInsn(INVOKEINTERFACE, "java/lang/System$Logger", "log",
"(Ljava/lang/System$Logger$Level;Ljava/lang/String;[Ljava/lang/Object;)V", true);
}
};
}
public static void main(String[] args) throws IOException {
Path path = Path.of(args[0]); // e.g. set/Item.class
var reader = new ClassReader(Files.readAllBytes(path));
var writer = new ClassWriter(reader, ClassWriter.COMPUTE_MAXS);
reader.accept(new EntryLogger(writer, reader.getClassName().replace('/', '.')),
ClassReader.EXPAND_FRAMES);
Files.write(path, writer.toByteArray()); // overwrite the class file
}
}
Compile the target class, run the tool on its class file, then run the program with the ASM JARs on the class path (Windows uses ; and doesn't escape *):
javac set/Item.java set/SetTest.java
javac -cp .:asm/\* bytecode/EntryLogger.java
java -cp .:asm/\* bytecode.EntryLogger set/Item.class
javap -c set.Item # the new instructions appear at the start of hashCode, equals, ...
java set.SetTest
When SetTest puts Item objects into a HashSet, you see an "Entering set.Item.hashCode" message for every insertion, and an "Entering set.Item.equals" message when an equal item is inserted a second time. The annotations acted as directives, and a bytecode tool carried them out by rewriting the instructions. The constant pool indexes in javap output depend on the class, so they'll differ from run to run of the tool.
The same with the Class-File API (Java 24+)
The JDK's Class-File API replaces visitors with immutable models and transforms. A sketch:
ClassFile cf = ClassFile.of();
ClassModel model = cf.parse(Files.readAllBytes(path));
byte[] result = cf.transformClass(model, ClassTransform.transformingMethodBodies(
method -> hasLogEntry(method), // look for RuntimeInvisibleAnnotations
new CodeTransform() {
@Override public void atStart(CodeBuilder code) {
code.ldc(loggerName) /* ... the same instructions as above ... */;
}
@Override public void accept(CodeBuilder code, CodeElement element) {
code.with(element); // copy the original code unchanged
}
}));
Because it ships with the JDK, it never lags behind new class file versions. Lagging behind is the main maintenance burden with ASM, whose users must upgrade it for every new Java release.
Modifying bytecodes at load time
Running an extra tool over class files complicates the build. An attractive alternative is to modify the bytecodes when the class is loaded. The java.lang.instrument API has a hook for installing a class file transformer, which must be installed before main runs. You do that with a Java agent, a library that is loaded to monitor or modify a program.
- Implement a class with a
premainmethod, called beforemain. It receives one agent argument string and anInstrumentationobject for installing hooks:
import java.lang.instrument.*;
import java.security.ProtectionDomain;
import org.objectweb.asm.*;
public class EntryLoggingAgent {
public static void premain(String arg, Instrumentation instr) {
instr.addTransformer(new ClassFileTransformer() {
@Override
public byte[] transform(ClassLoader loader, String className, Class<?> cl,
ProtectionDomain pd, byte[] data) {
if (!className.equals(arg.replace('.', '/'))) return null; // null = leave unchanged
var reader = new ClassReader(data);
var writer = new ClassWriter(reader, ClassWriter.COMPUTE_MAXS);
reader.accept(new EntryLogger(writer, arg), ClassReader.EXPAND_FRAMES);
return writer.toByteArray(); // loaded instead of the original
}
});
}
}
- Write a manifest that names the agent class:
Premain-Class: bytecode.EntryLoggingAgent
- Package the agent and manifest into a JAR, and start the program with
-javaagent:jarfile=argument:
jar cvfm EntryLoggingAgent.jar EntryLoggingAgent.mf bytecode/*.class
java -javaagent:EntryLoggingAgent.jar=set.Item -cp .:asm/\* set.SetTest
The transformer checks whether the class being loaded is the one named in the agent argument. If so, it runs EntryLogger and returns the modified bytes, which the JVM loads instead of the originals. Nothing is written to disk. It's "just-in-time" bytecode modification.

More about agents:
Agent-Classwith anagentmainmethod lets you attach an agent to an already running JVM through the Attach API.Instrumentation.retransformClassescan then modify classes that are already loaded, within limits: you can't add fields or methods.- Dynamically loading agents into a running JVM prints a warning since Java 21 (JEP 451), and a future release will disallow it by default. Use
-XX:+EnableDynamicAgentLoadingwhen you really need it. Agents given with-javaagentat startup are unaffected. - ByteBuddy offers a higher-level API on top of ASM, and Mockito, Hibernate and many agents use it.
A complete example
ASM isn't part of the JDK, and the Class-File API needs Java 24, so the runnable demo works at a lower level. It reads its own nested class's class file by hand. It checks the magic number and version, walks the constant pool, and lists every method with the annotations stored in RuntimeInvisibleAnnotations. Those are CLASS-retention @LogEntrys, which reflection reports as absent. Note that javac also copied the annotation onto the bridge method get()Ljava/lang/Object; that it generated for Supplier<String>. Then the demo modifies the bytecode before loading. It replaces the "Hello" constant in the constant pool, defines the patched bytes through its own class loader, and calls the new class, which is the same idea as a load-time transformer.
import java.io.*;
import java.lang.annotation.*;
import java.util.*;
import java.util.function.Supplier;
public class Solution {
// CLASS retention (the default): stored in the class file, invisible to reflection
@Retention(RetentionPolicy.CLASS) @Target(ElementType.METHOD)
@interface LogEntry { String logger(); }
public static class Greeter implements Supplier<String> {
@LogEntry(logger = "com.example.greet") public String get() { return "Hello"; }
@LogEntry(logger = "com.example.math") public int twice(int x) { return 2 * x; }
public int plain() { return 42; }
}
// ---------- a tiny class file reader ----------
record Member(String name, String descriptor, List<String> annotations) {}
static final class ClassFile {
final int major;
final String[] utf8; // constant pool UTF-8 entries by index
final Map<Integer, int[]> utf8Pos = new HashMap<>(); // index -> {offset, length}
final String thisClass;
final List<Member> methods = new ArrayList<>();
private final DataInputStream in;
private int pos;
ClassFile(byte[] bytes) throws IOException {
in = new DataInputStream(new ByteArrayInputStream(bytes));
if (u4() != 0xCAFEBABE) throw new IOException("not a class file");
u2(); // minor version
major = u2();
int count = u2();
utf8 = new String[count];
int[] classNameIndex = new int[count];
for (int i = 1; i < count; i++) {
int tag = u1();
switch (tag) {
case 1 -> { int start = pos; int len = u2(); byte[] b = bytes(len);
utf8[i] = new String(b, java.nio.charset.StandardCharsets.UTF_8); // fine for ASCII names
utf8Pos.put(i, new int[] { start, 2 + len }); }
case 7 -> classNameIndex[i] = u2();
case 8, 16, 19, 20 -> u2();
case 15 -> { u1(); u2(); }
case 3, 4, 9, 10, 11, 12, 17, 18 -> u4();
case 5, 6 -> { u4(); u4(); i++; } // long and double take two slots
default -> throw new IOException("unknown constant tag " + tag);
}
}
u2(); // access flags
thisClass = utf8[classNameIndex[u2()]];
u2(); // super class
skip(2 * u2()); // interfaces
readMembers(false); // fields
readMembers(true); // methods
}
private void readMembers(boolean keep) throws IOException {
int n = u2();
for (int i = 0; i < n; i++) {
u2();
String name = utf8[u2()], desc = utf8[u2()];
var anns = new ArrayList<String>();
int attrs = u2();
for (int a = 0; a < attrs; a++) {
String attrName = utf8[u2()];
int len = u4();
if (attrName.equals("RuntimeInvisibleAnnotations") || attrName.equals("RuntimeVisibleAnnotations")) {
int num = u2();
for (int k = 0; k < num; k++) anns.add(annotation() + (attrName.startsWith("RuntimeVisible") ? " (visible)" : " (invisible)"));
} else skip(len);
}
if (keep) methods.add(new Member(name, desc, anns));
}
}
private String annotation() throws IOException {
String type = utf8[u2()];
int pairs = u2();
var sb = new StringBuilder("@" + type.substring(type.lastIndexOf('$') + 1, type.length() - 1) + "(");
for (int p = 0; p < pairs; p++) {
if (p > 0) sb.append(", ");
sb.append(utf8[u2()]).append('=').append(elementValue());
}
return sb.append(')').toString();
}
private String elementValue() throws IOException {
char tag = (char) u1();
return switch (tag) {
case 's' -> '"' + utf8[u2()] + '"';
case 'B', 'C', 'D', 'F', 'I', 'J', 'S', 'Z', 'c' -> "#" + u2();
case 'e' -> { u2(); yield utf8[u2()]; }
case '@' -> annotation();
case '[' -> { int n = u2(); var parts = new ArrayList<String>(); for (int i = 0; i < n; i++) parts.add(elementValue()); yield parts.toString(); }
default -> throw new IOException("bad element value tag " + tag);
};
}
private int u1() throws IOException { pos += 1; return in.readUnsignedByte(); }
private int u2() throws IOException { pos += 2; return in.readUnsignedShort(); }
private int u4() throws IOException { pos += 4; return in.readInt(); }
private byte[] bytes(int n) throws IOException { byte[] b = new byte[n]; in.readFully(b); pos += n; return b; }
private void skip(int n) throws IOException { in.skipNBytes(n); pos += n; }
/** Returns new class file bytes with one UTF-8 constant replaced. */
static byte[] replaceUtf8(byte[] original, ClassFile cf, String oldValue, String newValue) throws IOException {
for (int i = 1; i < cf.utf8.length; i++) {
if (oldValue.equals(cf.utf8[i])) {
int[] p = cf.utf8Pos.get(i);
var out = new ByteArrayOutputStream();
out.write(original, 0, p[0]); // everything before the entry
var data = new DataOutputStream(out);
data.writeUTF(newValue); // u2 length + modified UTF-8 bytes
out.write(original, p[0] + p[1], original.length - p[0] - p[1]); // everything after
return out.toByteArray();
}
}
throw new IllegalArgumentException("constant not found: " + oldValue);
}
}
/** Defines one class from given bytes instead of delegating to the parent loader. */
static final class PatchingLoader extends ClassLoader {
private final String name; private final byte[] bytes;
PatchingLoader(String name, byte[] bytes) { super(Solution.class.getClassLoader()); this.name = name; this.bytes = bytes; }
@Override protected Class<?> loadClass(String n, boolean resolve) throws ClassNotFoundException {
if (n.equals(name)) {
synchronized (getClassLoadingLock(n)) {
Class<?> c = findLoadedClass(n);
return c != null ? c : defineClass(n, bytes, 0, bytes.length);
}
}
return super.loadClass(n, resolve);
}
}
public static void main(String[] args) throws Exception {
byte[] bytes;
try (InputStream in = Solution.class.getResourceAsStream("Solution$Greeter.class")) { bytes = in.readAllBytes(); }
System.out.println("-- reading the class file --");
var cf = new ClassFile(bytes);
System.out.println(" magic OK, class " + cf.thisClass + ", compiled for Java 17 or later: " + (cf.major >= 61));
for (Member m : cf.methods) System.out.println(" method " + m.name() + m.descriptor() + " " + m.annotations());
System.out.println("-- reflection cannot see CLASS-retention annotations --");
System.out.println(" Greeter.get() annotations via reflection: "
+ Greeter.class.getMethod("get").getAnnotations().length);
System.out.println("-- modifying the bytecode before loading --");
System.out.println(" original get(): " + new Greeter().get());
byte[] patched = ClassFile.replaceUtf8(bytes, cf, "Hello", "Hello from modified bytecode");
Class<?> patchedClass = new PatchingLoader(Greeter.class.getName(), patched).loadClass(Greeter.class.getName());
@SuppressWarnings("unchecked")
Supplier<String> g = (Supplier<String>) patchedClass.getDeclaredConstructor().newInstance();
System.out.println(" patched get(): " + g.get());
System.out.println(" same class name, different class: " + patchedClass.getName().equals(Greeter.class.getName())
+ ", " + (patchedClass != Greeter.class));
System.out.println(" patched file still parses, methods: "
+ new ClassFile(patched).methods.stream().map(Member::name).toList());
}
}
-- reading the class file --
magic OK, class Solution$Greeter, compiled for Java 17 or later: true
method <init>()V []
method get()Ljava/lang/String; [@LogEntry(logger="com.example.greet") (invisible)]
method twice(I)I [@LogEntry(logger="com.example.math") (invisible)]
method plain()I []
method get()Ljava/lang/Object; [@LogEntry(logger="com.example.greet") (invisible)]
-- reflection cannot see CLASS-retention annotations --
Greeter.get() annotations via reflection: 0
-- modifying the bytecode before loading --
original get(): Hello
patched get(): Hello from modified bytecode
same class name, different class: true, true
patched file still parses, methods: [<init>, get, twice, plain, get]
Common questions
Should I use ASM or the Class-File API?
For new tools on Java 24 or later, consider the Class-File API (java.lang.classfile). It ships with the JDK and always supports the latest class file version. ASM remains the choice when you must run on older JDKs or use libraries such as ByteBuddy that are built on it.
How do I see what's inside a class file?
Use javap. javap -c disassembles the bytecode, javap -v shows everything including the constant pool and the version, and javap -p includes private members.
Which major version corresponds to which Java release?
Subtract 44: major version 61 is Java 17, 65 is Java 21, and 69 is Java 25. A JVM refuses to load class files with a higher version than it supports, with an UnsupportedClassVersionError.
What is the difference between premain and agentmain?
premain runs when the agent is given with -javaagent at startup, before main. agentmain runs when the agent is attached to an already running JVM. Dynamic attach prints a warning since Java 21 and will be disabled by default in a future release.
Is bytecode engineering worth it for application code? Rarely. It's hard to debug and breaks with new Java versions. Use reflection or annotation processors for application features. Leave bytecode rewriting to infrastructure tools such as profilers, coverage tools, mocking libraries and tracing agents.
API reference
java.lang.instrument
| Method | Description |
|---|---|
static void premain(String agentArgs, Instrumentation inst) (agent class) | called before main for agents given with -javaagent:jar=args |
void Instrumentation.addTransformer(ClassFileTransformer t), addTransformer(t, boolean canRetransform) | registers a transformer for classes loaded from now on |
void Instrumentation.retransformClasses(Class<?>... classes) | re-runs transformers on already loaded classes (method bodies only) |
byte[] ClassFileTransformer.transform(ClassLoader loader, String className, Class<?> cl, ProtectionDomain pd, byte[] classfileBuffer) | returns modified bytes, or null to leave the class unchanged |
Related
| Item | Description |
|---|---|
javap -c, javap -v, javap -p | disassemble bytecodes; show constant pool and attributes; include private members |
ClassReader, ClassVisitor, ClassWriter, MethodVisitor, AdviceAdapter (ASM) | visitor-based reading, transformation and writing of class files |
java.lang.classfile.ClassFile.of().parse(bytes), transformClass(model, transform) | JDK Class-File API (Java 24) |
protected Class<?> ClassLoader.defineClass(String name, byte[] b, int off, int len) | turns class file bytes into a Class |
Summary
- Annotations with
CLASSorRUNTIMEretention are stored in class files, where bytecode tools can find them.CLASSretention suits markers that only tools need. - Class files hold a constant pool, members and attributes, including
Codeand the annotation attributes.javaplets you inspect them. - ASM's visitors (
ClassReader→ yourClassVisitor/AdviceAdapter→ClassWriter) can insert instructions such as entry logging. Java 24's Class-File API does the same with models and transforms and always tracks new class file versions. - A Java agent's
premainregisters aClassFileTransformerthat rewrites classes at load time without touching files. Dynamically attached agents now produce warnings. - Use bytecode engineering for infrastructure such as profiling, coverage, mocking and persistence, and prefer simpler techniques in application code.
Practice Questions
Why must the @LogEntry annotation not have SOURCE retention?
SOURCE annotations are discarded by the compiler and never reach the class file, so a bytecode tool couldn't find them. CLASS retention (the default) is enough, because they don't need to be visible to reflection at runtime.
What does a ClassFileTransformer return to leave a class unchanged?
It returns null, which tells the JVM to use the original bytes. Returning a byte array makes the JVM define the class from those bytes instead.
How do you start a program with a Java agent, and what must the agent JAR contain?
Run java -javaagent:agent.jar=argument -cp ... MainClass. The JAR must contain the agent classes and a manifest with a Premain-Class attribute naming the class that has the premain(String, Instrumentation) method.
What is the advantage of the JDK's Class-File API over ASM?
It's part of the JDK and is updated with every release, so it always understands the newest class file version. ASM is a separate library that must be upgraded when new Java versions introduce new class-file features. The Class-File API also uses immutable models and composable transforms rather than visitors.
In the demo, the annotation shows up on two get methods. Why?
Greeter implements Supplier<String>. Because of erasure, javac generates a synthetic bridge method Object get() that calls String get(), and it copies the method's annotations onto the bridge. Tools that rewrite methods must be aware of bridge methods.
Previous: Java Annotation Processors: Generating Source Code at Compile Time
Next: Java Modules Introduction: The Module Concept and a Hello World Module
Related reading
- Java Streams Explained: From Loops to Stream Pipelines
- Your First Java Program Explained: Classes, main, Statements and Comments
- What Is Java? The Language, the Platform, and the JVM Explained
- Java char, Unicode and boolean: Characters, Escape Sequences and Truth Values
- Java Annotation Processors: Generating Source Code at Compile Time

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.