In Java's Class-File API, how do models, builders and transforms fit together when rewriting a class, and how does that differ from ASM's visitors?
answer
- one vocabulary for reading and writing
- the builder arrives in a lambda
- a flat-map over elements
- what happens if you do nothing
- lifting a CodeTransform to a ClassTransform
basics
~20 sImmutable models expose a class as a sequence of elements, builders accept those same elements, and a transform decides for each element whether to keep, drop or replace it. ASM uses one visitor structure for reading and writing, driven by callbacks.
solid answer
~50 s`ClassFile.parse` turns bytes into an immutable, lazily inflated `ClassModel` you can walk as elements: fields, methods, attributes and, inside a method's `CodeModel`, instructions. Each model has a matching builder, handed to your lambda rather than constructed by you, and a builder accepts the same elements the model yields. A transform takes a builder and an element, so it acts as a flat-map: pass the element on with `with`, emit replacements, or do nothing, which drops it. You can write a small `CodeTransform`, lift it with `ClassTransform.transformingMethodBodies`, combine with `andThen` and run `ClassFile.transformClass`. ASM's streaming view uses visitors, and its `MethodVisitor` doubles as visitor and builder; here you match on element values instead. Because the builder sits in a lambda the library can re-run it, which by default it does for a final-stage handler when a forward short jump overflows.
code
java · 32 linesimport java.lang.classfile.ClassFile;
import java.lang.classfile.ClassModel;
import java.lang.classfile.ClassTransform;
import java.lang.classfile.CodeTransform;
import java.lang.classfile.MethodModel;
import java.lang.classfile.Opcode;
import java.lang.classfile.instruction.InvokeInstruction;
import java.lang.constant.ClassDesc;
public class RedirectCalls {
static byte[] rewrite(byte[] original) {
// One decision per element: replace the call, or hand the element on.
CodeTransform fooToBar = (builder, element) -> {
if (element instanceof InvokeInstruction call
&& call.opcode() == Opcode.INVOKESTATIC
&& call.owner().name().equalsString("Foo")) {
builder.invokestatic(ClassDesc.of("Bar"), call.name().stringValue(),
call.typeSymbol(), call.isInterface());
} else {
builder.with(element); // without this, the element is dropped
}
};
ClassTransform dropDebug = ClassTransform.dropping(element ->
element instanceof MethodModel method
&& method.methodName().stringValue().startsWith("debug"));
ClassFile classFile = ClassFile.of();
ClassModel model = classFile.parse(original);
return classFile.transformClass(model,
dropDebug.andThen(ClassTransform.transformingMethodBodies(fooToBar)));
}
}go deeper
Recall the three words: models describe an existing class, builders write a new one, and transforms sit between them deciding what each element becomes.
Explain the mechanics: why a builder accepts what a model yields, why a transform works like a flat-map, and how a CodeTransform gets lifted to a ClassTransform.
Show rewrite experience: code handlers that can run twice, state kept through ofStateful, a class hierarchy resolver for stack maps, and checking the output with ClassFile.verify.
Treat ASM versus this API as a portfolio decision: the ergonomics case comes from the API's own authors, so test it on your real transforms and weigh it against baselines and migration cost.
## Three abstractions JEP 484 builds the API from three ideas, repeated at each level of a class file. - **Element**: an immutable description of part of a class file, such as an instruction, attribute, field or method. A compound element, called a **model** here (`ClassModel`, `FieldModel`, `MethodModel`, `CodeModel`), also contains elements of its own and can be handled whole or taken apart. - **Builder**: the writing side. `ClassBuilder`, `FieldBuilder`, `MethodBuilder` and `CodeBuilder` accept their element type through `with` and add conveniences such as `CodeBuilder.aload`. - **Transform**: a functional interface taking a builder and an element. `ClassTransform`, `FieldTransform`, `MethodTransform` and `CodeTransform` match the four models. ## Reading: a lazy, immutable tree `ClassFile.of().parse(bytes)` returns a `ClassModel`, the root of a tree: the class holds fields, methods and attributes, a method holds its `CodeModel`, and the code holds instructions. You can go straight to a part with an accessor such as `model.methods()`, or iterate a model's elements and use pattern matching to pick out what you want. Parsing is lazy, so most of the file is not inflated until something asks for it. ## Writing: the builder comes to you You do not construct builders. `ClassFile.build` takes a class name and a lambda that receives a `ClassBuilder`; `ClassBuilder.withMethod` hands a `MethodBuilder` to the next lambda, and `MethodBuilder.withCode` hands on a `CodeBuilder`. The library derives what follows from those calls, including the constant pool and, by default, stack maps. ## Transforming: a flat-map over elements A builder accepts what a model yields, so rewriting needs no separate mode. For each element, a transform takes one of three courses: - **Keep** it with `builder.with(element)`. - **Replace** it by asking the builder for one or more other elements. - **Drop** it by doing nothing. A transform's hooks then run in a fixed order: 1. `atStart` runs before any element. 2. `accept` runs for each element. 3. `atEnd` runs after all of them. You write a transform at the smallest level that needs it and **lift** it: `MethodTransform.transformingCode` wraps a `CodeTransform`, `ClassTransform.transformingMethods` wraps a `MethodTransform`, and `ClassTransform.transformingMethodBodies` does both. `andThen` **composes** two transforms of one kind, feeding one's output to the next without an intermediate class. JDK 25 has a bug here, fixed in JDK 26: `andThen` between two class transforms lifted with method predicates applies both only where both predicates match, so a pair aimed at different methods silently changes nothing. Given a `CodeTransform` named `fooToBar`, the whole rewrite is: ```java ClassFile classFile = ClassFile.of(); byte[] rewritten = classFile.transformClass(classFile.parse(bytes), ClassTransform.transformingMethodBodies(fooToBar)); ``` ## Against ASM's visitors This table is JEP 484's framing, written by the API's authors, who also disclaim any aim of being the fastest library. | Aspect | ASM | Class-File API | |---|---|---| | Reading | Streaming view built on visitors, with calls such as `visitMethodInsn` | Iterating elements and matching on their types | | Writing | You create a `ClassWriter` and ask it for a `MethodVisitor`, both visitor and builder | You pass a lambda that receives a builder | | Rewriting | A common visitor structure for readers and writers | A flat-map over elements, written as lambdas | | Materialized view | Supported beside streaming | Same vocabulary as streaming, and claimed far cheaper through laziness | The lambda is more than style. Capturing the operations lets the library replay them: it can try short jump offsets first and, if that fails, discard the attempt and invoke the lambda again. ## Traps when rewriting a real class - **Silence drops.** A transform doing nothing on an element drops it, so `(builder, element) -> {}` yields a class with no methods or fields, while access flags and superclass fall back to the builder's defaults. `ClassTransform.ACCEPT_ALL` passes everything on. - **Handlers can run twice.** Under the default `ShortJumpsOption.FIX_SHORT_JUMPS`, an overflowing forward jump makes the internal `DirectCodeBuilder` call the code handler again. A counter in a handler that writes to that builder reads two on JDK 25 and 27, so outside side effects repeat; in an earlier stage of a class-level `andThen` the output is buffered and the counter reads one. `FAIL_ON_SHORT_JUMPS` throws instead. - **State needs a factory.** `CodeTransform.ofStateful` takes a supplier that creates a fresh transform per traversal, the re-run above included. - **Stack maps may need your classes.** The default `StackMapsOption.STACK_MAPS_WHEN_REQUIRED` reuses stack maps if the code stays compatible and otherwise generates them, which can consult a `ClassHierarchyResolver`. The default resolver cannot load classes from other class loaders, so generation can fail with `IllegalArgumentException` on a class outside the system class loader unless you set `ClassHierarchyResolverOption`. - **The pool is shared.** The default `ConstantPoolSharingOption.SHARED_POOL` extends the original constant pool, which makes untouched parts cheap to copy but can leave unused entries after large removals. `NEW_POOL` starts fresh. - **Immutable is not a thread-safety promise.** The package documentation warns that, because of laziness, models may not be thread safe, and that malformed data can surface as `IllegalArgumentException` from an accessor after `parse` has returned. - **Check your output.** Beyond null and representable-argument checks, the documentation promises no consistency checks while building, though fatal problems can still throw later. `ClassFile.verify` returns a list of `VerifyError`. Since JDK 26 many out-of-range `int` values that JDK 25 truncates silently are rejected: `ClassBuilder.withFlags(0x10001)` writes `0x1` on 25 and throws on 27.
- Why can a Class-File API code handler or CodeTransform run twice for one method, and what follows from that?Under the default `FIX_SHORT_JUMPS`, a forward short jump that overflows makes the internal builder discard its attempt and call the handler writing to it again, with such jumps in long form. So outside side effects, such as a counter or a log line, can repeat; an earlier stage of a class-level `andThen` is buffered and runs once. Keep handlers free of them, or set `FAIL_ON_SHORT_JUMPS` and take an `IllegalArgumentException` instead.
- How would you write a ClassTransform that adds a method only if the class does not already have it?Keep a flag. `accept` sets it on seeing that `MethodModel` and passes every element on with `builder.with`; `atEnd` adds the method if the flag is still unset. Create it through `ClassTransform.ofStateful(Supplier)` so each traversal gets a fresh flag when the transform is shared or reused.
- When would you set ClassFile.ConstantPoolSharingOption.NEW_POOL for a rewrite rather than keep the default?When the transform removes a lot. The default `SHARED_POOL` extends the original pool, which keeps indices intact, saves processing time and minimizes differences from the original, but the output can stay bigger because entries nothing uses remain. `NEW_POOL` creates a fresh pool holding what the new class asks for, at the cost of that optimization.
- Is a Class-File API ClassModel safe to share between threads because it is immutable?Not on that reasoning. The package documentation says models are immutable and inflated lazily, and warns that because of the laziness they may not be thread safe. Immutable describes the content, not a promise about concurrent access. The cautious default is to confine a model to one thread or parse once per thread.
A copy editor working through a manuscript: each paragraph goes into the new edition as it stands, rewritten, or not at all, and whatever is not handed to the typesetter simply does not appear. The original manuscript stays as it was.
- A transform edits the ClassModel in place, and the model then holds the change.
- Any element a transform ignores is copied across automatically.
- An immutable ClassModel can always be shared freely between threads.
- A code-building lambda always runs exactly once per method.
- Rewriting a class means maintaining its constant pool and stack maps by hand.
- Stack map generation never needs to know about classes outside the file.
- Class-File API (java.lang.classfile)
- Java 24pre-release 22
Assumes JDK 27. JDK 26 changed two things here that JDK 25 still does: truncating many out-of-range int arguments, and applying andThen between predicate-filtered method transforms only where both predicates match.
context
- JEP 484: Class-File APIopenjdk.org
- ClassFileTransform (Java SE 27 & JDK 27)docs.oracle.com
- java.lang.classfile (Java SE 27 & JDK 27)docs.oracle.com