-
Notifications
You must be signed in to change notification settings - Fork 2
Home
AutoRecord - Java record source generator
Google AutoValue has long been used as a way to work with Value Classes in an easy way. However, when Java records were introduced, they lacked some features that AutoValue had, such as nullability checking, builders, and memoization. This is why AutoRecord was created.
AutoRecord is a code generator that helps you easily generate Java records. It provides an easy way to avoid writing repetitive boilerplate code. It generates the code with features such as:
- nullability checking
- generated builder for the record
- memoization
-
ignoring fields in
hashCode
andequals
methods - generated common methods the record has an array component
- exclusion from JaCoCo test coverage analysis
📝 Note |
---|
Below, we will illustrate a record without a generated builder. If you want to learn how to use builders, please go to Builders page. |
Create your value class as an interface
, with an accessor method for each desired property, and annotate it with @AutoValue
annotation:
import pl.com.labaj.autorecord.AutoRecord;
@AutoRecord
interface Person {
String name();
int age();
}
AutoRecord will then generate a Java record
that implements your interface. The constructor parameters correspond, in order, to the interface methods:
import static java.util.Objects.requireNonNull;
import java.lang.String;
import javax.annotation.processing.Generated;
@Generated("pl.com.labaj.autorecord.AutoRecord")
record PersonRecord(String name, int age) implements Person {
PersonRecord {
requireNonNull(name, () -> "name must not be null");
}
}
You can create the record instance with canonical constructor then:
PersonRecord person = new PersonRecord("Joe", 25);
It is recommended to provide a factory method in your interface to make it easier to create instances of your record. This method should have a clear and descriptive name and take all required parameters for creating an instance of the record. Here is an example of what this might look like:
import pl.com.labaj.autorecord.AutoRecord;
@AutoRecord
interface Person {
String name();
int age();
static PersonRecord create(String name, int age) {
return new PersonRecord(name, age);
}
}
Add the following dependency to your pom.xml
file:
<dependency>
<groupId>pl.com.labaj</groupId>
<artifactId>auto-record</artifactId>
<version>${auto-record.version}</version>
</dependency>
Declare the following dependency in your build.gradle
script:
dependencies {
annotationProcessor 'pl.com.labaj:auto-record:${autoRecordVersion}'
}
Depending on your IDE you are likely to need to enable Annotation Processing in your IDE settings.