I recently discovered Java records, and it was amazing to learn about their existence and purpose.
However, I began to wonder if they are essentially just classes behind the scenes.
Does this mean that during compilation, they get converted into an explicit class with final private fields, a public constructor, and the necessary getters?
8
1 Answer
Under the hood it will still create a class (that’s derived from java.lang.Record
).
You can try it out yourself:
// test.java
record Test(int foo, String bar) {}
When you compile this with javac test.java
and disassemble it again with javap Test
you’ll get this code:
final class Test extends java.lang.Record {
Test(int, java.lang.String);
public final java.lang.String toString();
public final int hashCode();
public final boolean equals(java.lang.Object);
public int foo();
public java.lang.String bar();
}
1
-
What about at the machine code level? If e.g. a function creates and returns a
Record
with particular fields values, without persisting any other reference to the object, and the caller retrieves the fields and discards all references to the object after having done so, would the JVM be able to generate machine code that avoids the creation and abandonment of the object instance?– supercat5 hours ago
To quote for JEP 395: Records: "Enhance the Java programming language with records, which are classes that act as transparent carriers for immutable data." (emphasis mine). In total JEP 395 mentions the words "class" 86 times and "classes" 63 times. Basically everything (except primitives) are classes in Java, so it shouldn't come as a surprise that records are as well.
15 hours ago
Java class vs. record
15 hours ago
It really depends on what exactly you mean by "syntactic sugar", most people don't have a good definition of what they actually mean by that. Records are classes, as Mark pointed out. But whether or not they are "just syntactic sugar for regular classes" is really hard to answer without a firm definition.
15 hours ago
Given how record patterns (JEP 440: Record Patterns) only work for records, I would say that records are not just syntactic sugar for classes, as they offer features that are not available for "normal" classes.
15 hours ago
@MarkRotteveel: It looks like it's still syntactic sugar. It looks like they enable it via: 1) All
Record
s inherit from a single common superclass (java.lang.Record
). 2) They provide a function,Class.getRecordComponents
, that checks if the thing in question is aRecord
(viaClass.isRecord
, though I'm fairly sure that's equivalent to just checking if the superclass isjava.lang.Record
, due to the restrictive nature ofRecord
s), and if so, knows it can use reflection in a defined way to determine the components it can extract.6 hours ago