What is @NonNull?
Without Project Lombok
Without Lombok @NonNull annotation, we need to manually write a code to handle null pointer exceptions:package net.javaguides.lombok.nonnull;
import net.javaguides.lombok.User;
public class NonNullExample {
private String name;
public NonNullExample(User user) {
if (user == null) {
throw new NullPointerException("person is marked @NonNull but is null");
}
this.name = user.getFirstName();
}
public static void main(String[] args) {
NonNullExample example = new NonNullExample(null);
}
}
With Project Lombok
With Project Lombok, we are not writing any code to handle null pointer null but we are just adding @NonNull annotation:package net.javaguides.lombok.nonnull; import lombok.NonNull; import net.javaguides.lombok.User; public class NonNullLombokExample { private String name; public NonNullLombokExample(@NonNull User person) { this.name = person.getFirstName(); } public static void main(String[] args) { NonNullLombokExample example = new NonNullLombokExample(null); } }The @NonNull annotation automatically generates that null check for you.
Common Use Cases
Limitations and Considerations
Reference
GitHub Repository
You can view the source code of this article on my GitHub repository at https://github.com/RameshMF/project-lombok-tutorialContinue Learning with Java Guides
Want to take your programming skills to the next level? Explore my practical Udemy courses on Java, Spring Boot, Microservices, Full-Stack Development, Docker, and Generative AI. You can also follow my structured learning roadmaps to become a professional developer.
By Ramesh Fadatare - Udemy Instructor Partner
Comments
Post a Comment
Leave Comment