Records are a new language feature since Java 14 (first preview) and Java 15 (second preview). As per my understanding they will be used to reduce boilerplate code in immutable data objects.
So this sigle line:
public record Person (String firstName, String lastName) {}
Is equivalent to declaring a class with private final fields, getter for each field, a public constructor and equals, hashCode and toString methods.
However this is pretty much the same as using lombok @Value
annotation:
@Value
public class Person {
String firstName;
String lastName;
}
Other than you obviously doesn't need to deal with the lombok dependency, is there any advantange of using records?
Yes, records can do more than that. It also provides the equals, hashCode and toString automatically for you. So this works as well. So the record keyword can be considered as an equivalent to lombok's @Value annotation.
@Value is the immutable variant of @Data ; all fields are made private and final by default, and setters are not generated. The class itself is also made final by default, because immutability is not something that can be forced onto a subclass.
Lombok enables you to use @EqualsAndHashCode. Exclude for excluding components from the hashCode and equals method generation. To achieve the equivalent currently with Records, you should re-implement hashCode and equals yourself.
Since we use @Value mainly to create immutable objects, Lombok marks the class as final and the instance variables as private final. However, this isn't a strict rule. In the end, name and salary won't be final or private.
In addition to what Axel already suggested:
@Value
generates immutable java beans while record
is not a java bean.
Record is a built-in feature and it doesn't need any plugin or installation.
Lombok allows inheriting from a class while the record inherits j.l.Record
. Extending a class generates a warning which is self-explanatory:
Generating equals/hashCode implementation but without a call to superclass, even though this class does not extend java.lang.Object. If this is intentional, add '(callSuper=false)' to your type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With