Tuesday, April 18, 2023

How to use Lombok in Java? Lombok @Data and @NonNull Annotations Examples

Hello Java programmers, if you have been doing professional Java development, you may have heard about Lombok library, one of the most popular Java libraries among professional Java developers, making coding in Java much more fun and rewarding. Java has always been criticized for its verbosity, and many programming languages like Scala and Groovy are invented to solve that problem, but Lombok solves that problem in Java itself. This means you don't need to learn a new programming language, but you can use the Lombok library and its annotations to write clear and concise code in Java. 

If you love simplicity in your code, then you are going to love Lombok. This is a small library that is used to reduce the amount of boilerplate code in Java classes. Writing constructors, getters, and setters for each class are much more difficult than focusing on the class's business logic.

By using Lombok’s simple annotations, you can remove a lot of clutter form your Java code which makes your class and code much more readable. This also means that you just need to focus on the business logic in your class, and Lombok will take care of details need by the Java compiler and JVM

For example, Lombok can automatically generate getters and setters for those objects by using specific Lombok @Data annotations.

import lombok.Data;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
@Data
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private int studentId;
private String name;
private int age;
}


After adding the @Data annotation to your class, you will get the following methods for free without implementing each and every method. Lombok will automatically generate  getId(), getSummary(), getDescription(), setId(), setSummary(), SetDescription(), equals(), canEqual(), hashCode(), toString(), ToDo().

The best thing is that Lombok can be integrated with modern Java IDEs like IntellijIDEA and Eclipse, which do not show any error when you call these getter and setters on a Data object. They will know that Lombok is implementing them at compile time. Without enabling Lombok plugins, IDEs will throw errors like those annoying red lines. 




Advanced Lombok Features for Java Developers

Lombok provides many convenient annotations to make Java developers easier. You can also use things like val, var, @NonNull, @Cleanup, @Data, @Value, @Builder, @Singular, @Getter(lazy=true), @Log, @UtilityClass, and a slew of other useful functions are available to any developer. 

You may shorten your code and gain a high level of automation for regular tasks by using these.

The way this is working is by auto-generating the java bytecode into your classes whenever you build.

Let’s have another class to explain the Lombok library in java. Here we have a Java class with many code lines that have getters, setters, and constructors.



package com.example.studentproject.model;

public class Student {

private int studentId;
private String name;
private int age;

public Student(int studentId, String name, int age) {
  this.studentId = studentId;
  this.name = name;
  this.age = age;
}

public int getStudentId() {
  return studentId;
}

public void setStudentId(int studentId) {
  this.studentId = studentId;
}

public String getName() {
  return name;
}

public void setName(String name) {
  this.name = name;
}

public int getAge() {
  return age;
}

public void setAge(int age) {
  this.age = age;
}

@Override
public String toString() {
return "Student{" +
"studentId=" + studentId +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}


This is how usually we write the class in java. Declare the setters, getters, and constructors. But we can reduce the number of code lines that we used earlier without reducing the methods implemented using Lombok.

import lombok.*;
@ToString 
@Getter 
@Setter
@AllArgsConstructor
public class Student {
 private int studentId;
 private int  age;
 private String name;
 }

We have implemented the same functionality as the previous code by using the @ToString, @Getter, and @Setter. And also you can add as many Lombok annotations as you want to automatically generate code. 

How to use Lombok Library in Java? Example Tutorial




When to use Lombok and @Data Annotation Examples

Now, let's see some common examples of using the Lombok library in Java development. We will see examples of different Lombok Annotations like @Data and @NonNull, standard @Getter, @Setter, @ToString, etc.

1. @Data annotation Example

One trendy way of using Lombok is simply adding the @Data annotation to your class. This helps to reduce the amount of code (annotations to represent each function) using.

import lombok.Data;

@Data
public class Student {
int studentId, age;
String name;
}

This @Data annotation bundles all the @Getter / @Setter, @ToString, @EqualsAndHashCode, @Getter / @Setter, and @RequiredArgsConstructor annotations together. So, you don't need to use each of these annotations one by one; you can directly annotate your data class with @Data, and Lombok will take care of the details. 
 



2. Check for Null Values - @NonNull Example

The @NonNull annotation can be used to generate a null check on a setter field, which should not be confused with the Bean Validation annotation. If the annotated class field contains a null value, the check-raises a NullPointerException. We can simply apply this to a field to enforce the rule.

@NonNull @Setter
private String studentId;


From the above code, you can generate the following code.
public id setStudentId(@NonNull final String studentId) {

  if (studentId == null) {
   throw new java.lang.NullPointerException("studentId ");
 }
   this. studentId = studentId;

}

On primitive arguments, @NonNull annotations are not permitted. If they are, a warning is provided, and no null check is performed.

Here is another example of using Lombok in Java code:

How to use Lombok in Java? @Data and @NonNull Annotations Examples

  

That's all about what Lombok library is in Java and how to use Lombok to write better Java code. You have seen that Lombok annotations can greatly reduce the boiler plate code and make development faster and make your code clean and easier to read. 

So as a brief, the Lombok in java is not about reducing code but about clearly communicating what you desire to achieve, rather than having to figure it out from Javadoc or implementations. The reduced code just makes it easier to spot any divergent-method implementations.

Other Programming Resources and Articles You may like

Thanks for reading this Java Lombok tutorial so far. If you like these Lombok @Data and @NonNull annotation examples and explanation then please share them with your friends and colleagues on Facebook. If you have any questions or feedback then please drop a note.
    
P. S. - If you are new to the Java world and want to master Java before exploring these tools and library then you can also check out this list of Top 10 Advanced Core Java Courses on Medium. It contains different Java courses to become an expert Java programmer.

1 comment:

  1. Lombok is great, Can't imaging a Java project without Lombok nowadays.

    ReplyDelete