Class-File API
suggest changeThe package java.lang.classfile is the JDK's own library for reading, writing and transforming .class files. It became final in Java 24 (JEP 484), after previews in Java 22 and 23. It needs no flags and no extra dependencies. All the examples below were compiled and run with JDK 25.
Frameworks used to rely on third-party libraries for this, mostly ASM (see How to edit jar files with ASM), plus Javassist (Javassist Basic) and BCEL. Those libraries have one built-in problem. Each JDK release can bump the class-file version, and a library from before the release can refuse the new class files. So every framework that bundles ASM has to ship an update before its users can move to the new JDK. The Class-File API ships with the JDK, so it always understands the class files of the JDK it runs on.
The API is built from three ideas:
- Elements are immutable descriptions of parts of a class: a field, a method, an attribute, one instruction.
- Models are parsed, read-only views of compound elements:
ClassModel,FieldModel,MethodModel,CodeModel. A model is a sequence of its elements. - Builders create compound elements:
ClassBuilder,MethodBuilder,CodeBuilder. A transform is a function that gets each element of a model and a builder, and decides what to send to the builder.
Everything starts from a ClassFile object, created with ClassFile.of() (optionally with options, covered below).
Reading a class
ClassFile.parse() takes a byte[] or a Path and returns a ClassModel. Parsing is lazy, so parts of the class are decoded only when you look at them.
We'll use this class:
public class Greeter {
private final String name;
private int count;
public Greeter(String name) { this.name = name; }
public String greet() {
count++;
return "Hello, " + name + "!";
}
public static int square(int x) { return x * x; }
}
Listing its fields and methods:
import java.lang.classfile.*;
import java.nio.file.*;
public class ListMembers {
public static void main(String[] args) throws Exception {
byte[] bytes = Files.readAllBytes(Path.of(args[0]));
ClassModel cm = ClassFile.of().parse(bytes);
System.out.println("class " + cm.thisClass().asInternalName()
+ " extends " + cm.superclass().get().asInternalName()
+ " (version " + cm.majorVersion() + ")");
for (FieldModel f : cm.fields()) {
System.out.println(" field " + f.fieldName() + " " + f.fieldType()
+ " " + f.flags().flags());
}
for (MethodModel m : cm.methods()) {
System.out.println(" method " + m.methodName() + m.methodType()
+ " " + m.flags().flags());
}
}
}
$ javac Greeter.java ListMembers.java
$ java ListMembers Greeter.class
class Greeter extends java/lang/Object (version 69)
field name Ljava/lang/String; [PRIVATE, FINAL]
field count I [PRIVATE]
method <init>(Ljava/lang/String;)V [PUBLIC]
method greet()Ljava/lang/String; [PUBLIC]
method square(I)I [PUBLIC, STATIC]
Version 69 is Java 25. Names and types come back as constant-pool entries (Utf8Entry, ClassEntry) printed in the class-file format, so class names use / and types are descriptors like Ljava/lang/String;. Compare names with equalsString("greet") instead of converting them to String first. flags().flags() returns a Set<AccessFlag>.
Walking the bytecode
A method's code is a CodeModel, a sequence of CodeElements. Most elements are instructions, and each kind of instruction has its own interface in java.lang.classfile.instruction, so you can use pattern matching to pick the ones you care about (see Pattern matching). Debug information such as line numbers shows up as pseudo-instructions in the same stream.
import java.lang.classfile.*;
import java.lang.classfile.attribute.CodeAttribute;
import java.lang.classfile.instruction.*;
import java.nio.file.*;
public class DumpCode {
public static void main(String[] args) throws Exception {
ClassModel cm = ClassFile.of().parse(Path.of("Greeter.class"));
for (MethodModel m : cm.methods()) {
if (!m.methodName().equalsString("greet")) continue;
CodeAttribute code = m.findAttribute(Attributes.code()).orElseThrow();
System.out.println("maxStack=" + code.maxStack()
+ " maxLocals=" + code.maxLocals());
for (CodeElement e : code) {
switch (e) {
case FieldInstruction f -> System.out.println(" " + f.opcode()
+ " " + f.owner().asInternalName() + "." + f.name()
+ " " + f.type());
case InvokeDynamicInstruction indy -> System.out.println(" "
+ indy.opcode() + " " + indy.name() + indy.type());
case LoadInstruction l -> System.out.println(" "
+ l.opcode() + " slot " + l.slot());
case Instruction i -> System.out.println(" " + i.opcode());
default -> System.out.println(" ; " + e);
}
}
}
}
}
maxStack=3 maxLocals=1
; LineNumber[line=8]
ALOAD_0 slot 0
DUP
GETFIELD Greeter.count I
ICONST_1
IADD
PUTFIELD Greeter.count I
; LineNumber[line=9]
ALOAD_0 slot 0
GETFIELD Greeter.name Ljava/lang/String;
INVOKEDYNAMIC makeConcatWithConstants(Ljava/lang/String;)Ljava/lang/String;
ARETURN
m.code() returns an Optional<CodeModel>, which is empty for abstract and native methods. To get maxStack and maxLocals we asked for the Code attribute directly with findAttribute(Attributes.code()). That returns a CodeAttribute, which is also a CodeModel.
This is the same information javap -c prints (see Viewing bytecode with javap), but as objects you can query.
Analysing many classes
Models work well with streams. elementStream() streams the elements of any compound element. The class files of the running JDK can be read through the jrt: file system. This counts which classes java.util.ArrayList calls into most:
import java.lang.classfile.*;
import java.lang.classfile.instruction.InvokeInstruction;
import java.net.URI;
import java.nio.file.*;
import java.util.*;
import java.util.stream.*;
public class Calls {
public static void main(String[] args) throws Exception {
// class files of the running JDK are readable through the jrt: file system
Path p = Path.of(URI.create("jrt:/java.base/java/util/ArrayList.class"));
ClassModel cm = ClassFile.of().parse(p);
Map<String, Long> byOwner = cm.methods().stream()
.flatMap(m -> m.code().stream())
.flatMap(CompoundElement::elementStream)
.filter(e -> e instanceof InvokeInstruction)
.map(e -> ((InvokeInstruction) e).owner().asInternalName())
.collect(Collectors.groupingBy(o -> o, TreeMap::new, Collectors.counting()));
byOwner.entrySet().stream()
.sorted(Map.Entry.<String, Long>comparingByValue().reversed())
.limit(5)
.forEach(en -> System.out.println(en.getValue() + "\t" + en.getKey()));
}
}
48 java/util/ArrayList
20 java/lang/StringBuilder
10 java/util/ConcurrentModificationException
9 java/util/Objects
8 java/lang/System
Run the same loop over every entry of a jar (FileSystems.newFileSystem(jarPath)) and you have a simple dependency checker, for example one that fails the build when code calls System.exit.
Generating a class
ClassFile.build() takes the class name as a ClassDesc and a lambda that configures a ClassBuilder. Types are described with the nominal descriptors from java.lang.constant: ClassDesc for classes, MethodTypeDesc for method signatures, and ready-made constants such as CD_int, CD_String, CD_void and INIT_NAME ("<init>") in ConstantDescs.
withMethodBody adds a method and passes you a CodeBuilder. It has one fluent method for each JVM instruction (iload, imul, invokevirtual, return_, ...), plus some higher-level helpers.
import java.lang.classfile.*;
import java.lang.constant.*;
import java.lang.reflect.AccessFlag;
import java.nio.file.*;
import static java.lang.constant.ConstantDescs.*;
public class Generate {
static final ClassDesc CD_System = ClassDesc.of("java.lang.System");
static final ClassDesc CD_PrintStream = ClassDesc.of("java.io.PrintStream");
public static void main(String[] args) throws Exception {
byte[] bytes = ClassFile.of().build(ClassDesc.of("Hello"), clb -> clb
.withFlags(AccessFlag.PUBLIC, AccessFlag.FINAL)
// public static int square(int x) { return x * x; }
.withMethodBody("square", MethodTypeDesc.of(CD_int, CD_int),
ClassFile.ACC_PUBLIC | ClassFile.ACC_STATIC,
cob -> cob.iload(0).iload(0).imul().ireturn())
// public static void main(String[] args) {
// System.out.println("5 squared is " + square(5)); (without indy)
// }
.withMethodBody("main", MethodTypeDesc.of(CD_void, CD_String.arrayType()),
ClassFile.ACC_PUBLIC | ClassFile.ACC_STATIC,
cob -> cob
.getstatic(CD_System, "out", CD_PrintStream)
.ldc("5 squared is ")
.invokevirtual(CD_PrintStream, "print",
MethodTypeDesc.of(CD_void, CD_String))
.getstatic(CD_System, "out", CD_PrintStream)
.iconst_5()
.invokestatic(ClassDesc.of("Hello"), "square",
MethodTypeDesc.of(CD_int, CD_int))
.invokevirtual(CD_PrintStream, "println",
MethodTypeDesc.of(CD_void, CD_int))
.return_()));
Files.write(Path.of("Hello.class"), bytes);
System.out.println("wrote " + bytes.length + " bytes");
}
}
$ java Generate
wrote 372 bytes
$ java Hello
5 squared is 25
$ javap -c Hello.class
public final class Hello {
public static int square(int);
Code:
0: iload_0
1: iload_0
2: imul
3: ireturn
public static void main(java.lang.String[]);
Code:
0: getstatic #12 // Field java/lang/System.out:Ljava/io/PrintStream;
3: ldc #14 // String 5 squared is
5: invokevirtual #20 // Method java/io/PrintStream.print:(Ljava/lang/String;)V
8: getstatic #12 // Field java/lang/System.out:Ljava/io/PrintStream;
11: iconst_5
12: invokestatic #22 // Method square:(I)I
15: invokevirtual #26 // Method java/io/PrintStream.println:(I)V
18: return
}
We never touched the constant pool, and we didn't compute the maximum stack depth. The library does both. It also builds the StackMapTable attribute the verifier needs for any method with branches, which is the most tedious part of writing bytecode by hand. When no superclass is given, it defaults to java.lang.Object. The class version defaults to the current JDK's (69 for JDK 25).
Branches, locals and loading the class
The next example generates an implementation of IntUnaryOperator that computes a factorial, with a constructor, an if, a loop and a thrown exception. It then loads the class at runtime with MethodHandles.Lookup.defineClass(), which defines a class in the same package and class loader as the lookup.
import java.lang.classfile.*;
import java.lang.constant.*;
import java.lang.invoke.MethodHandles;
import java.util.function.IntUnaryOperator;
import static java.lang.classfile.ClassFile.*;
import static java.lang.constant.ConstantDescs.*;
public class Factorial {
public static void main(String[] args) throws Exception {
ClassDesc self = ClassDesc.of("GeneratedFactorial");
byte[] bytes = ClassFile.of().build(self, clb -> clb
.withFlags(ACC_PUBLIC | ACC_FINAL | ACC_SUPER)
.withSuperclass(CD_Object)
.withInterfaceSymbols(ClassDesc.of("java.util.function.IntUnaryOperator"))
// public GeneratedFactorial() { super(); }
.withMethodBody(INIT_NAME, MTD_void, ACC_PUBLIC, cob -> cob
.aload(0)
.invokespecial(CD_Object, INIT_NAME, MTD_void)
.return_())
// public int applyAsInt(int n) {
// if (n < 0) throw new IllegalArgumentException();
// int result = 1;
// while (n > 1) { result *= n; n--; }
// return result;
// }
.withMethodBody("applyAsInt", MethodTypeDesc.of(CD_int, CD_int), ACC_PUBLIC, cob -> {
ClassDesc iae = ClassDesc.of("java.lang.IllegalArgumentException");
int n = cob.parameterSlot(0);
int result = cob.allocateLocal(TypeKind.INT);
Label loop = cob.newLabel();
Label done = cob.newLabel();
cob.iload(n)
.ifThen(Opcode.IFLT, b -> b
.new_(iae).dup()
.ldc("negative argument")
.invokespecial(iae, INIT_NAME, MethodTypeDesc.of(CD_void, CD_String))
.athrow());
cob.iconst_1().istore(result)
.labelBinding(loop)
.iload(n).iconst_1().if_icmple(done)
.iload(result).iload(n).imul().istore(result)
.iinc(n, -1)
.goto_(loop)
.labelBinding(done)
.iload(result).ireturn();
}));
Class<?> c = MethodHandles.lookup().defineClass(bytes);
IntUnaryOperator fact = (IntUnaryOperator) c.getConstructor().newInstance();
for (int i = 0; i <= 5; i++) {
System.out.println(i + "! = " + fact.applyAsInt(i));
}
System.out.println(c.getName() + " implements " + c.getInterfaces()[0].getSimpleName());
try {
fact.applyAsInt(-1);
} catch (IllegalArgumentException e) {
System.out.println("caught " + e);
}
}
}
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
GeneratedFactorial implements IntUnaryOperator
caught java.lang.IllegalArgumentException: negative argument
Things to notice:
parameterSlot(0)returns the local-variable slot of the first parameter. In an instance method that's 1, because slot 0 holdsthis.allocateLocal(TypeKind.INT)reserves a new slot, and alongordoublegets two. Asking the builder for slots is safer than hard-coding numbers.- A
Labelis created withnewLabel()and placed withlabelBinding(). Branch instructions such asif_icmpleandgoto_can jump forward to labels that aren't bound yet. ifThen(Opcode.IFLT, ...)is a structured helper. It creates the labels for you and runs the lambda only when the condition holds. There are alsoifThenElse,blockandtrying(for try/catch).- Because
GeneratedFactorialimplements an interface we compiled against, the rest of the program uses it through that interface, with no reflection after the constructor call. This is the usual pattern for generated code.
Mistakes are caught early
Bytecode that the JVM would reject usually fails while you build it, because the library has to work out the stack at every instruction to produce stack maps. Some type errors get past that step. ClassFile.verify() runs the JVM's verification rules on a class without loading it:
import java.lang.classfile.*;
import java.lang.constant.*;
import java.lang.invoke.MethodHandles;
import static java.lang.constant.ConstantDescs.*;
public class Bad {
public static void main(String[] args) throws Exception {
// 1. stack underflow: caught while building, because computing
// stack maps needs a consistent operand stack
try {
ClassFile.of().build(ClassDesc.of("Broken1"), clb -> clb
.withMethodBody("oops", MethodTypeDesc.of(CD_int), ClassFile.ACC_STATIC,
cob -> cob.iconst_1().iadd().ireturn())); // iadd needs two ints
} catch (IllegalArgumentException e) {
System.out.println("build: " + e.getMessage().lines().findFirst().get());
}
// 2. wrong type: returns a String from an int method. Builds fine...
byte[] bytes = ClassFile.of().build(ClassDesc.of("Broken2"), clb -> clb
.withMethodBody("oops", MethodTypeDesc.of(CD_int), ClassFile.ACC_STATIC,
cob -> cob.ldc("not an int").ireturn()));
// ...but verify() finds the problem without loading the class
for (VerifyError err : ClassFile.of().verify(bytes)) {
System.out.println("verify: " + err.getMessage().lines().findFirst().get());
}
// and so would the JVM
try {
MethodHandles.lookup().defineClass(bytes);
} catch (VerifyError e) {
System.out.println("JVM: " + e.getMessage().lines().findFirst().get());
}
}
}
build: Operand stack underflow at bytecode offset 1 of method oops()
verify: Bad type on operand stack in Broken2::oops() @2 (integer_type is not assignable from java/lang/String)
JVM: Bad type on operand stack
The full build error message also includes a dump of the method's bytecode, which helps a lot when debugging a generator. Running verify() in your generator's tests is cheap and gives better messages than a VerifyError from class loading.
Transforming a class
Most real uses change existing classes: add logging, remove a method, redirect calls. In the Class-File API, a transform is a function (builder, element) -> void, with one interface per level: ClassTransform, MethodTransform, FieldTransform and CodeTransform. ClassFile.transformClass(model, transform) walks the model and calls your transform for each element:
builder.with(element)keeps the element unchanged,- not calling the builder drops the element,
- calling other builder methods adds or replaces elements.
A transform may also override atStart(builder) and atEnd(builder) to add elements before the first or after the last element. Transforms compose with andThen.
Here is a small program we'll rewrite:
public class Shop {
public static void main(String[] args) {
Shop s = new Shop();
System.out.println("total = " + s.total(3, 250));
s.debugDump();
}
int total(int qty, int price) {
return applyDiscount(qty * price);
}
int applyDiscount(int amount) {
return amount > 500 ? amount - 50 : amount;
}
void debugDump() {
System.out.println("internal state dump");
}
}
The transformation removes debugDump() and adds a log line at the start of every method. Dropping a method isn't enough on its own, because main still calls it and would throw NoSuchMethodError. So a CodeTransform also replaces each invokevirtual debugDump with pop, which discards the Shop reference that was pushed as the receiver.
import java.lang.classfile.*;
import java.lang.classfile.instruction.InvokeInstruction;
import java.lang.constant.*;
import java.nio.file.*;
import static java.lang.constant.ConstantDescs.*;
public class Instrument {
static final ClassDesc CD_System = ClassDesc.of("java.lang.System");
static final ClassDesc CD_PrintStream = ClassDesc.of("java.io.PrintStream");
static final MethodTypeDesc MTD_println = MethodTypeDesc.of(CD_void, CD_String);
// a CodeTransform that prints "-> name" before the original code
static CodeTransform logEntry(String name) {
return new CodeTransform() {
@Override
public void atStart(CodeBuilder cob) {
cob.getstatic(CD_System, "out", CD_PrintStream)
.ldc("-> " + name)
.invokevirtual(CD_PrintStream, "println", MTD_println);
}
@Override
public void accept(CodeBuilder cob, CodeElement e) {
cob.with(e); // keep every original element
}
};
}
public static void main(String[] args) throws Exception {
ClassFile cf = ClassFile.of();
ClassModel cm = cf.parse(Path.of("Shop.class"));
// 1. remove the debugDump() method ...
ClassTransform dropDebug = ClassTransform.dropping(e ->
e instanceof MethodModel m && m.methodName().equalsString("debugDump"));
// 2. ... replace every call to it with POP, which discards the receiver ...
CodeTransform removeCalls = (cob, e) -> {
if (e instanceof InvokeInstruction i && i.name().equalsString("debugDump")) {
cob.pop();
} else {
cob.with(e);
}
};
// 3. ... and log entry to every other method except constructors
ClassTransform logging = (clb, ce) -> {
if (ce instanceof MethodModel mm
&& mm.code().isPresent()
&& !mm.methodName().equalsString(INIT_NAME)) {
String name = mm.methodName().stringValue();
clb.transformMethod(mm, MethodTransform.transformingCode(logEntry(name)));
} else {
clb.with(ce);
}
};
byte[] out = cf.transformClass(cm, dropDebug
.andThen(ClassTransform.transformingMethodBodies(removeCalls))
.andThen(logging));
Files.createDirectories(Path.of("out"));
Files.write(Path.of("out", "Shop.class"), out);
}
}
$ javac Shop.java Instrument.java
$ java Instrument
$ java -cp . Shop
total = 700
internal state dump
$ java -cp out Shop
-> main
-> total
-> applyDiscount
total = 700
javap -c -cp out Shop shows the rewritten main:
public static void main(java.lang.String[]);
Code:
0: getstatic #10 // Field java/lang/System.out:Ljava/io/PrintStream;
3: ldc #62 // String -> main
5: invokevirtual #24 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
8: new #7 // class Shop
11: dup
12: invokespecial #9 // Method "<init>":()V
15: astore_1
16: getstatic #10 // Field java/lang/System.out:Ljava/io/PrintStream;
19: aload_1
20: iconst_3
21: sipush 250
24: invokevirtual #16 // Method total:(II)I
27: invokedynamic #20, 0 // InvokeDynamic #0:makeConcatWithConstants:(I)Ljava/lang/String;
32: invokevirtual #24 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
35: aload_1
36: pop
37: return
Look at the constant-pool indexes: #10, #16 and #24 are the same as in the original class, and only the new string -> main was appended (#62). By default a transformed class keeps the original constant pool and adds to it. Unchanged methods are copied as raw bytes without being decoded, which keeps transforms fast. The branch offsets in applyDiscount were recomputed, and new stack maps were generated, even though we inserted instructions before them.
The helpers used here, ClassTransform.dropping, transformingMethodBodies and MethodTransform.transformingCode, cover the common cases. When you need more context (here, the method name inside a code transform), write the class-level lambda yourself as logging does.
Using it from a Java agent
A Java agent's ClassFileTransformer receives the raw bytes of each class as it's loaded and may return new bytes (see Modifying classes with agents). That's exactly the input and output of transformClass, so the Class-File API can replace ASM in agents without any dependency.
This agent measures the running time of every method in classes whose internal name starts with app/. It stores System.nanoTime() in a new local at method entry, and calls a helper before every return instruction:
package agent;
import java.lang.classfile.*;
import java.lang.classfile.instruction.ReturnInstruction;
import java.lang.constant.*;
import java.lang.instrument.*;
import java.security.ProtectionDomain;
import static java.lang.constant.ConstantDescs.*;
public class TimingAgent {
static final ClassDesc CD_System = ClassDesc.of("java.lang.System");
static final ClassDesc CD_Timing = ClassDesc.of("agent.Timing");
public static void premain(String args, Instrumentation inst) {
String prefix = args == null ? "app/" : args; // internal name prefix
inst.addTransformer(new ClassFileTransformer() {
@Override
public byte[] transform(ClassLoader loader, String className,
Class<?> redefined, ProtectionDomain pd,
byte[] bytes) {
if (className == null || !className.startsWith(prefix)) {
return null; // null means "leave this class alone"
}
try {
return addTiming(bytes);
} catch (Throwable t) {
t.printStackTrace(); // exceptions thrown here are swallowed by the JVM
return null;
}
}
});
}
static byte[] addTiming(byte[] bytes) {
ClassFile cf = ClassFile.of();
ClassModel cm = cf.parse(bytes);
String owner = cm.thisClass().asInternalName().replace('/', '.');
return cf.transformClass(cm, ClassTransform.transformingMethods(
mm -> mm.code().isPresent() && !mm.methodName().stringValue().startsWith("<"),
(mb, me) -> {
if (!(me instanceof CodeModel code)) { mb.with(me); return; }
String label = owner + "." + code.parent().orElseThrow().methodName();
mb.transformCode(code, new CodeTransform() {
int start; // local slot holding the start time
@Override
public void atStart(CodeBuilder cob) {
start = cob.allocateLocal(TypeKind.LONG);
cob.invokestatic(CD_System, "nanoTime", MethodTypeDesc.of(CD_long))
.lstore(start);
}
@Override
public void accept(CodeBuilder cob, CodeElement e) {
if (e instanceof ReturnInstruction) {
// Timing.record(label, start) before every return
cob.ldc(label).lload(start)
.invokestatic(CD_Timing, "record",
MethodTypeDesc.of(CD_void, CD_String, CD_long));
}
cob.with(e);
}
});
}));
}
}
package agent;
public final class Timing {
public static void record(String method, long startNanos) {
long micros = (System.nanoTime() - startNanos) / 1_000;
System.out.printf("[timing] %s took %d us%n", method, micros);
}
}
The application knows nothing about the agent:
package app;
public class Main {
public static void main(String[] args) throws Exception {
System.out.println("fib(25) = " + fib(25));
slow();
}
static int fib(int n) {
int a = 0, b = 1;
for (int i = 0; i < n; i++) { int t = a + b; a = b; b = t; }
return a;
}
static void slow() throws InterruptedException {
Thread.sleep(20);
}
}
Build the agent jar with a Premain-Class manifest entry and start the app with -javaagent:
$ printf 'Premain-Class: agent.TimingAgent\n' > manifest.txt
$ javac -d classes src/agent/*.java src/app/*.java
$ jar --create --file timing-agent.jar --manifest manifest.txt -C classes agent
$ java -cp classes -javaagent:timing-agent.jar app.Main
[timing] app.Main.fib took 356 us
fib(25) = 75025
[timing] app.Main.slow took 21206 us
[timing] app.Main.main took 34248 us
(The times vary from run to run.) A few points apply to any agent:
allocateLocalpicks a slot past all the locals the original method uses, so the injectedlongcan't overwrite the method's own variables.- Only normal returns are timed. To time methods that exit by throwing, wrap the original body in a try/finally-style handler, for example with
CodeBuilder.exceptionCatchAll, and record the time before rethrowing. - An exception thrown from
transformis silently ignored by the JVM and the class loads unchanged, so catch and log it yourself. - The injected code calls
agent.Timing, so that class must be visible to the instrumented classes. Here both are on the application class path. To instrument JDK classes you would add the helper to the bootstrap class path (Boot-Class-Pathin the manifest).
Options
ClassFile.of(...) takes options that change how classes are parsed and written. Some useful ones:
| Option | Effect |
|---|---|
StackMapsOption.DROP_STACK_MAPS / GENERATE_STACK_MAPS |
Control stack-map generation (default: generate when needed) |
DebugElementsOption.DROP_DEBUG |
Drop local-variable tables and similar debug info |
LineNumbersOption.DROP_LINE_NUMBERS |
Drop line numbers |
ConstantPoolSharingOption.NEW_POOL |
Rebuild the constant pool from scratch instead of extending the original |
DeadCodeOption.KEEP_DEAD_CODE |
Keep unreachable code instead of patching it |
ClassHierarchyResolverOption.of(...) |
Tell the stack-map generator about classes it can't load itself |
A class stripper that removes debug information and the SourceFile attribute:
import java.lang.classfile.*;
import java.nio.file.*;
public class Strip {
public static void main(String[] args) throws Exception {
System.out.println("latest major version: " + ClassFile.latestMajorVersion());
byte[] original = Files.readAllBytes(Path.of("Greeter.class"));
ClassFile stripper = ClassFile.of(
ClassFile.DebugElementsOption.DROP_DEBUG,
ClassFile.LineNumbersOption.DROP_LINE_NUMBERS,
ClassFile.ConstantPoolSharingOption.NEW_POOL);
byte[] stripped = stripper.transformClass(stripper.parse(original),
ClassTransform.dropping(e -> e instanceof Attribute<?> a
&& a.attributeName().equalsString("SourceFile")));
System.out.println(original.length + " -> " + stripped.length + " bytes");
// a class file from the future is rejected
original[7] = (byte) (ClassFile.latestMajorVersion() + 1);
try {
ClassFile.of().parse(original);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
}
$ javac -g Greeter.java
$ javac Strip.java
$ java Strip
latest major version: 69
1007 -> 805 bytes
Unsupported class file version: 70
Without NEW_POOL the result is 999 bytes. The attributes are gone, but their names and strings stay in the shared constant pool.
The last lines show the versioning rule: the API in JDK N reads and writes class files up to version N, and rejects newer ones. A tool that runs on the JDK it processes is never out of date. A tool that has to read class files from a newer JDK than the one it runs on still needs a library like ASM.
Class hierarchy for stack maps
To generate stack maps, the library sometimes has to find the common superclass of two types, for example when two branches leave different types in the same local variable. By default it loads class information through the system class loader. That doesn't work for classes that exist only in your generator or in a jar you are processing. In that case the build fails with an IllegalArgumentException such as Could not resolve class A. You fix it by passing a resolver that can find those classes:
ClassFile cf = ClassFile.of(ClassFile.ClassHierarchyResolverOption.of(
ClassHierarchyResolver.defaultResolver().orElse(
ClassHierarchyResolver.ofResourceParsing(myJarClassLoader))));
Class-File API, ASM and Javassist
- ASM has a visitor API and a tree API. The Class-File API's models resemble the tree API and its transforms resemble the visitor chain, but they use records, sealed interfaces and lambdas instead of subclassing visitors. Code written against ASM can be ported piece by piece. The JDK itself moved its internal uses of ASM (lambdas, proxies,
jlinkplugins) to this API. - Javassist lets you write injected code as Java source strings. The Class-File API works only at the bytecode level, so you need to know the instructions (the
javap -coutput of a hand-written equivalent is the best reference). - Supported versions: the Class-File API needs Java 24+ at runtime but can write class files for any older version (
withVersion(ClassFile.JAVA_17_VERSION, 0)). Libraries that still support Java 17 or 21 keep using ASM, or include both and choose at runtime.
Summary
java.lang.classfile(final in Java 24, JEP 484) reads, writes and transforms class files with no dependencies, and always supports the running JDK's class-file version.ClassFile.of().parse()gives an immutableClassModel. Walk fields, methods and instructions with pattern matching or streams.ClassFile.of().build()generates classes withClassBuilder/CodeBuilder, usingClassDesc/MethodTypeDescfor types. The constant pool, max stack/locals, branch offsets and stack maps are computed for you. Load the result withMethodHandles.Lookup.defineClass()or a class loader.transformClass()appliesClassTransform/MethodTransform/CodeTransformfunctions:with(e)keeps an element, skipping it drops it, andatStart/atEndadd code. Compose transforms withandThen.- It fits directly into a Java agent's
ClassFileTransformer, replacing ASM there. - Use
verify()in tests, and supply aClassHierarchyResolverwhen generating code that refers to classes the generator can't load.