What does javac emit in the class file for a Java record, and how do equals, hashCode and toString reach ObjectMethods?
answer
- still an ordinary class file
- one extra class-file attribute
- one invokedynamic in each method body
- one bootstrap, separate call sites
- fields read, accessors bypassed
basics
~20 sFor a Java record, javac emits a final class extending java.lang.Record with private final fields, public accessors, a canonical constructor and a Record attribute; each undeclared equals, hashCode or toString is one invokedynamic to ObjectMethods.bootstrap.
solid answer
~40 sOn JDK 27, a record compiles to an ordinary class file: `final`, with `java.lang.Record` as direct superclass, a `private final` field and `public` accessor per component, a canonical constructor (implicitly, with the record's own access), and a `Record` attribute listing the components. Undeclared `equals`, `hashCode` and `toString` are `public final` and hold a single `invokedynamic`, whose bootstrap is `ObjectMethods.bootstrap`, given the record class, the component names and one `REF_getField` handle per component. Each call site links on first execution to a permanent `ConstantCallSite` built from method handles, so there is no per-call reflection. Because the handles read fields, overriding an accessor does not change `equals`. The JLS describes the results, not `invokedynamic`, and `Record`'s Javadoc calls the algorithm unspecified.
code
java · 15 linespublic class RecordInternals {
record Clipped(int x) {
@Override public int x() { return Math.min(x, 100); }
}
public static void main(String[] args) {
Clipped a = new Clipped(200);
Clipped copy = new Clipped(a.x());
System.out.println(a); // Clipped[x=200]
System.out.println(a.x()); // 100
System.out.println(a.equals(copy)); // false
System.out.println(Clipped.class.getSuperclass().getName()); // java.lang.Record
System.out.println(Clipped.class.getRecordComponents()[0]); // int x
}
}go deeper
Recall the shape behind the syntax: a final class extending java.lang.Record, one private final field and public accessor per component, and a canonical constructor.
Explain that generated equals, hashCode and toString have bodies built around one invokedynamic, that their logic appears at link time through a bootstrap method, and that they read component fields rather than accessors.
Show you have read javap output: REF_getField arguments, the Record attribute, linking on first call. Separate what the JLS promises from javac's and the JDK's private choices, and never persist a record's hashCode or parse its toString.
The tradeoff is a stable class-file shape against a strategy that moves with the runtime: a team gets JDK improvements without recompiling, but must not build caches or tooling on today's hash values or string format.
## What a record compiles to A **record class** is a restricted kind of class (JLS §8.10), not a new class-file format. javac turns it into an ordinary `.class` file in which every member is spelled out. For `public record Point(int x, String label) {}`, `javap -p` from JDK 27 prints: ```text public final class Point extends java.lang.Record { private final int x; private final java.lang.String label; public Point(int, java.lang.String); public final java.lang.String toString(); public final int hashCode(); public final boolean equals(java.lang.Object); public int x(); public java.lang.String label(); } ``` | Item | Class-file form | Worth saying | |---|---|---| | Class | `ACC_FINAL`, with `java/lang/Record` as `super_class` | `Record` is an abstract class, and javac rejects a hand-written `class X extends Record` | | Component field | `private final`, same name and type | A record cannot declare other instance fields | | Accessor | `public`, `getfield` then return | Not generated when you declare it yourself | | Canonical constructor | Calls `Record.<init>`, then one `putfield` per component | The implicit form has the record's own access, so it is not always `public` | | `equals`, `hashCode`, `toString` | `public final`, one `invokedynamic` each | Each is generated only if you did not declare it | | `Record` attribute | Name, descriptor and attributes of each component | `Class.getRecordComponents()` returns what is parsed from here | | `BootstrapMethods` entry | Points at `ObjectMethods.bootstrap` | Gone once you declare all three methods | ## Why each of the three methods holds one `invokedynamic` `invokedynamic` is a JVM instruction whose call target is not named in the class file: a **bootstrap method** supplies it when the instruction links. `hashCode` compiles to seven bytes of bytecode, and the bootstrap entry carries everything else as static arguments: ```text 0: aload_0 1: invokedynamic #21, 0 // InvokeDynamic #0:hashCode:(LPoint;)I 6: ireturn BootstrapMethods: 0: #44 REF_invokeStatic java/lang/runtime/ObjectMethods.bootstrap:(...)Ljava/lang/Object; Method arguments: #8 Point #40 x;label #42 REF_getField Point.x:I #43 REF_getField Point.label:Ljava/lang/String; ``` Linking then runs in this order: 1. The first execution of the instruction makes the JVM call `ObjectMethods.bootstrap` with a full-privilege lookup on the record class, the method's name and type, and those static arguments. 2. `bootstrap` switches on the name, and a private builder (`makeEquals`, `makeHashCode` or `makeToString`) composes a method handle. 3. `bootstrap` returns a `ConstantCallSite`, whose target is permanent, and the JVM binds it to that one instruction. 4. Later executions invoke that target; the JVMS says the bootstrap is not re-executed for them. Each method has its own instruction, so each links on its own first call. In a JDK 27 run with `-Xlog:class+load`, `java.lang.runtime.ObjectMethods` loaded only at the first call of a generated method, after the record was constructed, and a run that called none did not load it. ## What the composed handles do at JDK 27 This is private code, and `Record`'s Javadoc calls the precise algorithm unspecified and subject to change. What the methods must return is the generated members' contract; this is only how JDK 27 builds it: - **`equals`** tests identity, then `Class.isInstance`, then a chain of component tests. A JDK 27 run compared the last component first, which `Record.equals` allows. - **`hashCode`** starts at 0 and folds the components in order through the private `hashCombiner`, `x*31 + y`. The Javadoc says the result need not stay consistent between executions, so never persist it. - **`toString`** feeds a recipe to `StringConcatFactory.makeConcatWithConstants`, and splits long records at the private `MAX_STRING_CONCAT_SLOTS` limit of 20. The Javadoc says the format should not be parsed. - **Non-final component types**, meaning interfaces, non-final classes and arrays, get a hidden class at `equals` and `hashCode` linking: `record Cart(List<String> items)` gets `Cart$$HasherSpecializer` and `Cart$$EqualatorSpecializer`. Each holds a real `invokevirtual` or `invokeinterface` per such component because, in the source's words, a method handle to `Object.equals` "does not enjoy separate profiles like individual invokevirtuals". A JDK 27 run of a record with `int`, `String` and `double` components spun neither specializer, though it still loaded about 30 other hidden classes, mostly `java.lang.invoke.LambdaForm` ones. The specializer code first appears in JDK 26. JDK 25 LTS has none: its private `equalator` and `hasher` use shared handles to `Objects.equals` and `Objects.hashCode`. A `Cart` class file compiled on 25 spun none on 25 and both on 27. ## Fields, not accessors The `REF_getField` arguments are the part a candidate can observe. The `getters` parameter's Javadoc says "method handles for the accessor methods", but javac passes field getters, and JLS §8.10.3 settles the semantics: the methods look at "the values of component fields directly, rather than by invoking accessor methods". So an accessor that clips a value changes what callers read and leaves `equals`, `hashCode` and `toString` alone. A copy built through that accessor is then not equal to the original, which the JLS calls bad style. ## What is promised, and what is javac's choice - **Promised:** the implicit members and what their results derive from (JLS §8.10) and the `Record` attribute's format (JVMS §4.7.30). - **Not promised:** `invokedynamic` itself. No JLS chapter mentions it, and `ObjectMethods`' Javadoc says its methods "may be used, for example, by Java compiler implementations". - **What it buys:** method bodies of seven or eight bytes, and a strategy that lives in `java.base`, so a class file links against the `ObjectMethods` of the JDK it runs on. JDK 27's javac emits the same shape under `--release 16`. - **What it costs:** linking work at the first call of each method for each record class, visible in class-load logging.
- Why does overriding a record's accessor leave its generated equals unchanged?javac hands `ObjectMethods.bootstrap` one `REF_getField` handle per component, not the accessor, and JLS §8.10.3 says the generated methods look at component fields directly. A clipping accessor therefore changes only what callers read. Copying a record through that accessor gives an instance that is not equal to the original, which the JLS calls bad style.
- How does the JVM tell a record from a class that merely extends java.lang.Record?`Class.isRecord()` requires `Record` as direct superclass, the `final` flag and, through the native `isRecord0`, components parsed from the `Record` attribute. javac refuses `class X extends Record`, but a generated class file can have that superclass. On JDK 27, one without the attribute returns `false` from `isRecord()` and `null` from `getRecordComponents()`.
- Can java.lang.reflect.Field overwrite the private final field javac generates for a record component?No. `Field`'s Javadoc lists a record's final fields as non-modifiable, so `setAccessible(true)` enables reading only and `set` throws `IllegalAccessException`. HotSpot's `ciField.cpp` also trusts those fields when compiling, although the general `TrustFinalNonStaticFields` flag defaults to false. An object a component refers to can still be mutable, so this is not deep immutability.
- What extra classes can a Java record with a List component cause at runtime?From JDK 26, when `equals` or `hashCode` first links and a component's static type is not final, including interfaces and arrays, `ObjectMethods` defines a hidden specializer, such as `Cart$$HasherSpecializer`, beyond the hidden classes linking also loads, mostly `java.lang.invoke.LambdaForm` ones. It holds a real `invokevirtual` or `invokeinterface` so HotSpot profiles those components separately. JDK 25 LTS defines no specializer, and neither does JDK 27 for `int`, `String` and `double` components. This is private, unspecified behaviour.
- javac writes field-by-field comparison bytecode into the body of a record's equals method.
- The JLS requires the implicit equals, hashCode and toString of a record to use invokedynamic.
- Overriding a record's accessor changes what the generated equals and hashCode look at.
- ObjectMethods walks a record's components with reflection on every equals call.
- A record's implicit canonical constructor is always public, whatever the record's own access.
- java.lang.Record is a marker interface, so a record's direct superclass is still Object.
- Record classes
- Java 16pre-release 14
- java.lang.runtime.ObjectMethods
- Java 16pre-release 14
- Record attribute in the class file
- Java 16pre-release 14
- invokedynamic call sites
- Java 1.7
Assumes JDK 27; records are final since 16; ObjectMethods' hidden specializers for non-final component types arrived in JDK 26, so JDK 25 LTS has none.
context
- Chapter 8. Classesdocs.oracle.com
- Chapter 4. The class File Formatdocs.oracle.com
- ObjectMethods.java at jdk-27-gagithub.com