The @NoArgsConstructor
annotation is a feature of Lombok.
It automatically generates a no-argument constructor for your class.
This can be particularly useful when you need a default constructor but don’t want to manually write it out.
Here’s a basic example of how to use @NoArgsConstructor
:
import lombok.NoArgsConstructor;
@NoArgsConstructor
public class MyTestClass {
private String name;
private int age;
}
In this example, Lombok will generate the following no-argument constructor:
public MyTestClass() {
// No initialization logic
}
This is useful in various situations, such as:
- Serialization Libraries: Some libraries, like Jackson for JSON processing, require a no-argument constructor to deserialize objects.
- Frameworks: Certain frameworks or libraries might need a no-argument constructor for instantiating objects via reflection.
To use Lombok, you’ll need to include it as a dependency in your project and have the Lombok plugin installed in your IDE. For Maven, include it in your pom.xml
like so:
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.34</version>
<scope>provided</scope>
</dependency>
With
@NoArgsConstructor
, you save time and reduce boilerplate, making your code more maintainable.