skip to content

Class-File API

java.lang.classfile reads, writes and transforms class files with an API the JDK ships and updates each release, so tools lag less on new versions. Interviewers ask why it exists beside ASM.

part ofJavaread it →
on this pageshow

questions

2

What is Java's Class-File API (java.lang.classfile), and why did the JDK add it when ASM already existed?

level: middleimportance: nice to knowfreq 24%

answer

  1. a format that changes every six months
  2. library older than the class files
  3. javac held back until N+1
  4. a stated non-goal about existing libraries
  5. parse versus latestMajorVersion

basics

~20 s

The Class-File API (java.lang.classfile, final in Java 24) is the JDK's standard library for parsing, generating and transforming class files. It exists so tools and the JDK track the class-file format without waiting on a bundled library such as ASM.

solid answer

~50 s

`java.lang.classfile` is the standard API in `java.base` for reading, writing and transforming class files: preview in JDK 22 and 23, final in JDK 24 through JEP 484. The main driver is version skew rather than a defect in ASM. The class-file format can now change every six months, so frameworks meet class files newer than the library they bundle, and the JDK was caught too: ASM for JDK N could not finalize until after N did, so `javac` could not safely emit new features until N+1. Merging ASM was rejected because of its legacy baggage and what lambdas, records, sealed classes and pattern matching now allow. A tool on this API handles what its running JDK supports and no more: `ClassFile.parse` throws `IllegalArgumentException` above `ClassFile.latestMajorVersion()`. Obsoleting ASM is an explicit non-goal, though the JDK's own copy is gone from the 25 and 27 runtime images.

code

java · 15 lines
java
import java.lang.classfile.ClassFile;
import java.lang.classfile.ClassModel;
import java.lang.classfile.MethodModel;
import java.nio.file.Path;

public class ListMethods {
    public static void main(String[] args) throws Exception {
        System.out.println("This JDK reads major versions up to " + ClassFile.latestMajorVersion());
        ClassModel model = ClassFile.of().parse(Path.of(args[0]));
        System.out.println(model.thisClass().asInternalName() + ", major " + model.majorVersion());
        for (MethodModel method : model.methods()) {
            System.out.println(method.methodName().stringValue() + method.methodType().stringValue());
        }
    }
}

go deeper

for a junior

Recall that it is a JDK package for reading, writing and changing class files, final in Java 24, so that job needs no extra library.

for a middle

Explain version skew on both sides: frameworks bundle a library older than the class files they meet, and the JDK had to wait for ASM before javac could safely emit new features.

for a senior

Show you know the limit: parsing fails above the running JDK's latest major version, and sealed element types can grow, so decide whether each transform passes unknown elements through or fails fast.

for a principal

Weigh moving a framework off a bundled library against its supported baseline: Java 24 as a floor and rewritten bytecode code, in return for no longer waiting on a third party's release.

## What it is A **class file** is the compiled binary form of a class or interface: what `javac` writes and the JVM loads. Each Java release has a **major version** number for the format, 69 for Java 25 and 71 for Java 27. Plenty of software works on these files directly: frameworks that generate bytecode on the fly to add behaviour, build tools, analyzers and the JDK's own tools. The **Class-File API** is the JDK's standard library for that work. It lives in the package `java.lang.classfile` and three subpackages (`attribute`, `constantpool`, `instruction`), all exported by `java.base`, so it needs no dependency. Its entry point is `ClassFile`, a context that holds processing options: `parse` turns bytes into an immutable `ClassModel`, `build` generates a class and `transformClass` rewrites one. **ASM** is the long-established third-party library for the same job. ## The problem: version skew JEP 484, which finalized the API, starts from a fact about the release train: the format can now evolve every six months, and it has been evolving to support features such as sealed classes, dynamic constants and nestmates. Two separate failures follow. - **Frameworks fall behind.** A framework usually bundles a class-file library. When applications move to a newer JDK, the framework meets class files newer than its library. The JEP describes the result as errors visible to application developers or, worse, framework developers parsing class files from the future on a leap of faith. - **The JDK held itself back.** The JDK used an internal copy of ASM for tools such as `jar` and `jlink` and for lambda support at run time. The ASM version for JDK N could not finalize until after JDK N did, so tools in JDK N could not handle class-file features new in N, and `javac` could not safely emit them until N+1. The diagnosis matters in an interview: the JEP's complaint here is a third-party release schedule coupled to a platform format, not that ASM produces wrong bytes. ## Why not merge ASM into the JDK The JEP considers that option and rejects it, for two reasons: - ASM is, in its words, an old code base with legacy baggage that is difficult to evolve. - The language has changed since the visitor design of 2002. Lambdas, records, sealed classes and pattern matching, plus the `java.lang.constant` descriptors, allow an API the JEP calls more flexible and less error-prone. Its goals are to track the format defined by the JVM specification and to let JDK components migrate so the internal ASM copy can go. Its non-goals are as telling: - obsoleting existing class-file libraries, or being the fastest one; - extending Core Reflection to expose the bytecode of loaded classes; - providing code analysis, which third-party libraries can layer on top. ## What "tracks the format" does not promise Because the API ships inside the JDK, the class-file versions a tool can read are the versions its **running JDK** supports. Moving to a new JDK brings the matching library with no third-party release to wait for, but the version check has not gone away. `ClassFile.parse` documents an `IllegalArgumentException` for a version above `ClassFile.latestMajorVersion()`: | Running JDK | `latestMajorVersion()` | Parsing a class compiled for Java 27 (major 71) | |---|---|---| | 25 | 69 | `IllegalArgumentException`: `Unsupported class file version: 71` | | 27 | 71 | Works | More limits follow from the same fact: - A tool that must still run on a release before 24 cannot rely on the final API there. On 22 and 23 it was a preview API, and it changed afterwards: JEP 484 lists the renames. - New elements can still break code. `ClassFileElement`'s documentation says the sealed element interfaces may gain members as the format evolves, and that an exhaustive `switch` over them ties the code to one platform version. An API fix in JDK 25 shows the cost with no format change involved: `CodeModel` began delivering `CustomAttribute` and `UnknownAttribute`, and the release note warns that such switches then fail to compile. - The documentation recommends a split. A transform interested in only some elements passes the rest through; one that consumes every element should throw on a newer JDK, a newer class file or an unknown element. ## Where it stands | JDK | Status | JEP | |---|---|---| | 22 | First preview | 457 | | 23 | Second preview | 466 | | 24 | Final | 484 | The migration goal has been carried through. In JDK 27 the package-private `InnerClassLambdaMetafactory`, which creates a class per lambda call site, imports `java.lang.classfile`, and neither the JDK 25 nor the JDK 27 runtime image holds an ASM package. Nothing obliges frameworks to follow, and one with a baseline older than 24 cannot depend on the final API anyway.

  • A build tool running on JDK 25 must read class files compiled for Java 27. What happens if it uses java.lang.classfile?
    `ClassFile.parse` throws `IllegalArgumentException`, because the file's major version, 71, is above `ClassFile.latestMajorVersion()`, which is 69 on JDK 25. The API follows the JDK it runs on, not the newest release. The usual fix is to run the tool on a JDK at least as new as the classes it reads.
  • Does JEP 484 mean a framework should drop ASM?
    Not by itself. Obsoleting existing libraries is an explicit non-goal, and so is being the fastest one. Moving removes the wait for a third-party update, but it costs a Java 24 baseline and rewriting the framework's bytecode code. A framework that still supports older releases cannot use the final API on them.
  • Can the Class-File API give you the bytecode of a class that is already loaded?
    Not on its own. JEP 484 lists extending Core Reflection to expose the bytecode of loaded classes as a non-goal. The API works on bytes you supply through `parse(byte[])` or `parse(Path)`, so getting those bytes, for example from a class path resource, is your job.
  • How should a Class-File API transform treat elements it does not recognize, given that the format keeps growing?
    It depends on what the transform promises. The package documentation says one interested in only some elements can pass the rest through with `builder.with(element)` in a `default` branch, which keeps working. One that consumes every element should throw on a newer JDK, a newer class file or an unknown element, rather than guess.

  • ASM was simply merged into the JDK and renamed java.lang.classfile.
  • The API was added because ASM generates wrong bytecode, not because of version skew.
  • A tool built on the Class-File API can parse class files from any future JDK.
  • Frameworks must migrate now because the JDK has deprecated ASM.
  • It is still a preview API, so using it requires --enable-preview at Java 27.
  • It extends reflection so you can read the bytecode of any loaded class.

Class-File API (java.lang.classfile)
Java 24pre-release 22

Assumes JDK 27; the Class-File API was a preview in JDK 22 and 23 and is final since JDK 24 (JEP 484).

context

open as a page

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?

level: seniorimportance: nice to knowfreq 13%

basics

~20 s

Immutable 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.

open as a page