Using Records with Java 14
Java 14 came out with records as a preview feature. Records are boilerplate-free, immutable DTO-like data structures. For my personal use cases, I was able to replace all uses of Lombok with Records.
Proceed with caution
Records is a preview feature. Preview features are implementation complete, but not permanent - they can change or be removed in future JDK releases. It is not advisable to publish any artifacts compiled with preview features enabled - they will be incompatible with applications that are not compiled with preview features. I think it is fine to use those in self-contained services with no shared code artifacts, keeping in mind that migration might be required in subsequent JDK releases. But that’s just me - proceed at your own risk.
Enabling preview features for applications built with Gradle
To compile an application with preview features enabled, --enable-preview
argument has to be passed to the Java compiler.
In Gradle this is done by configuring the JavaCompile
task:
tasks.withType(JavaCompile) {
options.compilerArgs += '--enable-preview'
}
Next thing is runtime - --enable-preview
has to be passed as an argument to the java
command. This comes in several flavors.
Firstly - tests - they are executed in the JVM and the JVM has to have the --enable-preview
argument to chew the bytecode compiled with preview features.
tasks.withType(Test) {
jvmArgs += '--enable-preview'
}
Then comes running the application itself. If this is done via Gradle’s JavaExec task:
tasks.withType(JavaExec) {
jvmArgs += '--enable-preview'
}
If the code is packaged and deployed to run somewhere, the JVM still has to be told about the preview features in use.
This can be done by adding the --enable-preview
argument to the JAVA_OPTS
environment variable.
Example
Here is an example that builds a very simple Java application that uses Records.
It uses the application
plugin to bundle the compiled code.
The application is then packaged into a Docker container to be shipped and executed in the target environment.
Note how the preview features are enabled via JAVA_OPTS
environment variable in the Dockerfile.
Also note how array equality is treated in records.