Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java record vs lombok @Value [duplicate]

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?

like image 744
pepevalbe Avatar asked Feb 16 '21 09:02

pepevalbe


People also ask

Does Java record replace Lombok?

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.

What is the difference between @data and @value Lombok?

@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.

Does Lombok work with records?

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.

What does @value do in Lombok?

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.


1 Answers

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.

like image 139
Aniket Sahrawat Avatar answered Oct 03 '22 23:10

Aniket Sahrawat