Nullbeans

Your source for software and tech info

The Ultimate Lombok Annotations Guide

In this post, we will discuss the different annotations that are offered by Lombok and what are the effects of these annotations on Java classes. If you haven’t already, please make sure to check our guide on how to add Lombok to your Spring boot project . This will help you get up and running with Lombok in your Spring boot (or any other kind of Java) application.

We will classify the different available annotations into three categories. First are the annotations that you could add on your class’ inner variables. Then we will explore method annotations. Finally, we will discuss class level annotations which you can add to your classes.

Inner member annotations

The @Getter annotation is used to generate a getter for a field. The annotation can be applied to any inner , static or final field.

By default, the generated getter will be public. However, you can change the access level by setting it in the annotation.

The code above will set the getter’s access level to protected.

The @Setter annotation behaves the same as the getter. It will generate a setter for the field with public access level. However, it will not work if you add it to a final variable and your IDE will probably complain about that.

You can also set the access level of the generated setter using the access level value.

The @NonNull annotation will add a null check to any methods that set the field such as setters and constructors. If an attempt to set the field with a null value is performed, a NullPointerException is thrown with the name of the field mentioned in the exception.

The @With annotation is used to generate a method which makes a copy of the object, but with a modified value of the annotated field. This annotation needs to be combined with an @AllArgsConstructor annotation in order to work (or you could manually create the constructor). For example:

This will generate a method with the name .withName . This generates a copy of the object, with all fields having the same value except for the field which is annotated with the @With annotation. An example usage of the generated code can be found below.

Method level Annotations

@synchronized.

The @Synchronized annotation is a method level annotation. According to Lombok, using this annotation is preferred over using Java’s synchronized keyword because unlike the synchronized keyword which locks on this , the annotation will synchronize the method on an inner variable. If the annotation is added to a static method, then it will lock on a static variable.

The lock object will be generated by the Lombok automatically if you do not explicitly define it.

In the first method, Lombok will generate a lock with the name $Lock. The second one will use the lockObj inner field as the lock. The equivalent code of the second method is as follows.

Please note that only one lock object will be generated by Lombok for all the inner methods and one lock will be generated for all static methods annotated with the @Synchronized . If you want to use a different lock per method, then you will need to define a different lock object per method.

@SneakyThrows

The @SneakyThrows is an annotation that could be added to a method which throws a checked exception. This allows you to omit adding the “throws …” clause to the method’s signature.

Any methods which then call this method can use it without having to declare the throws clause, a try and catch or another @SneakyThrows.

However, you need to be careful when using this annotation as you will no longer be able to write catch clause for these checked exceptions .

The @SneakyException is one of those Lombok features which you need to use carefully and with a lot of consideration as it might be hard to de-Lombok your code later on if the need arises.

Please also check out the official documentation of this annotation before considering using it.

Class level annotations

The @Getter annotation can be added to the class instead of a field. This will cause Lombok to add a getter to each field in the class.

The @Setter annotation will add a setter to each non-final field in the class. An example usage is as follows.

@NoArgsConstructor

The @NoArgsConstructor adds a zero arguments constructor to the class. It can be used as follows.

You can change the access level of the constructor by configuring it in the annotation.

You also have the option to generate a “static constructor”. This is a static method that encapsulates the original constructor. If you add a static name to the constructor, then Lombok will generate a static method which encapsulates the no args constructor. The generated no-args constructor will be private.

The static constructor can be used as follows.

@AllArgsConstructor

This annotation will add a constructor with an argument list of the same length and order as the inner fields that exist in the class. For example.

This class will have a constructor that can be used as follows.

Just like the NoArgsConstructor annotation, this annotation can also be used to created a static version of the constructor. This can be done by setting the staticName value.

@RequiredArgsConstructor

The @RequiredArgsConstructor is a Lombok annotation which will generate a constructor with only the required fields. Required fields are non-initialized final fields and fields annotated with @NonNull . Take for example the following class.

The generated constructor will contain only arguments for the required1 and required2 fields.

Again, as with all other constructor annotations, you can set the access level or generate a static version of the constructor.

The @Builder annotation is one of those interesting annotations from Lombok as it provides you with a builder pattern interface for the annotated class.

Take for example the following class.

This will generate a builder which can be used to generate an instance of the class. An example usage can be found below.

The builder class name, access level and other properties are configurable. We will explore these configurations in more detail in a later post.

@Singular with @Builder

The @Singular annotation is not a class level annotation. However, we could not introduce it before introducing the @Builder annotation.

This annotation can be added to collections in Java classes and is combined with the @Builder annotation. The result is that Lombok will add builder interface methods that modify that collection. For example:

This will automatically add the methods .snail(String snail) to add an item to the collection and a . clearSnails() to empty the collection. This will also automatically initialize a new instance of the List. An example usage could look as follows.

This is a class level annotation which could be used to generate a toString method. By default, the method includes all fields of the class. However, individual fields could be excluded using the exclude property of the annotation. For example:

Let us call the toString method of this class:

The value of x here will be:

@EqualsAndHashCode

The @EqualsAndHashCode annotation is added to the class to generate an .equals(..) and a .hashCode() methods. Just like the @ToString annotation, you could exclude fields using the exclude property. For example:

You can also configure the annotation by instructing it to include only the fields which are annotated with an @EqualsAndHashCode.Include annotation.

This will generate the methods with only the “close” variable.

The @Data annotation is kind of an all in one package. It is equivalent to adding the annotations @Getter @Setter @RequiredArgsConstructor @ToString @EqualsAndHashCode to your class.

In this post, we discussed the most widely used annotations from Lombok. However, there are some annotations which we have not discussed such as the @CleanUp and @Value. This is because these annotations deserve a post of their own.

Also note that this post serves as an introduction to the most essential annotations in Lombok. However, in real world applications, you will encounter situations which were not covered in this tutorial. For example, what happens when inheriting from a Lombok annotated classes? Can you override annotations from Superclasses? etc..

Therefore, please stay posted by following us on twitter and subscribing to our newsletter in order to be notified of the latest posts about Lombok.

Related Posts

  • How to create a CRUD REST API in Spring Boot
  • How to validate REST calls in Spring Boot
  • Error handling in REST and Spring Boot
  • Integrate OWASP dependency-check reports with SonarQube
  • Using PUT vs PATCH when building a REST API in Spring
  • How to use Java Bean Validation in Spring Boot
  • Identity & Security
  • Engineering
  • Announcements
  • Try Auth0 For Free Talk To Sales

list of all lombok annotations

A Complete Guide to Lombok

Let’s see everything you should know to start using Project Lombok. We will have a look at how to integrate it into your IDE and use it to avoid boilerplate code.

Antonello Zanini avatar

July 29, 2021

Java is a great but verbose language. You may be ending up writing many lines of code even to achieve the most common goals. Plus, it definitely involves repetitive code, like getters and setters. This leads to a huge amount of boilerplate and avoidable code. Not only does this add nothing to the business logic of your application, but writing it is an unnecessarily boring and time-consuming process. This is why you should start employing tools and libraries to make you more productive by avoiding this. That’s where Lombok comes into play!

This Java library provides you with several annotations aimed at avoiding writing Java code known to be repetitive and/or boilerplate. Project Lombok works by plugging into your build process. Then, it will auto-generate the Java bytecode into your .class files required to implement the desired behavior, based on the annotations you used. Thus, each annotation offered by Project Lombok allows you to skip writing methods and logic you would like to avoid, like constructors, equals, and hash code functions. This will save you a lot of time and let you focus on the business logic of your project. Plus, you will be able to keep your codebase smaller, cleaner, and easier to be read and maintained.

First, we will see what Project Lombok is and how it works. Then, we will study the most common and relevant Lombok’s annotations, understanding what the most important ones are, where, and how to use them. Next, it will be time to see how to integrate it in your IDE ( Integrated Development Environment ) and why you should not be afraid of using it.

Prerequisites

This is the list of all the prerequisites to replicate the examples that will be shown next:

  • Java >= 1.8
  • Gradle >= 4.x or Maven 3.6.x
  • Project Lombok >= 1.18.20

What is Lombok

Project Lombok (from now on, Lombok ) is an annotation-based Java library that allows you to reduce boilerplate code. Lombok offers various annotations aimed at replacing Java code that is well known for being boilerplate, repetitive, or tedious to write. For example, by using Lombok, you can avoid writing constructors with no arguments, toString ( ) , equals ( ) , and hashCode ( ) methods by simply adding a few annotations. The magic happens during the compile-time when the library injects the bytecode representing the desired and boilerplate code into your .class files. Plus, as we will see, the library can be plugged into your IDE, letting you have the same experience as if you had written all the boilerplate code yourself.

You can easily install Lombok by adding lombok to your dependencies. If you are a Gradle user , add these two lines to the dependencies section of your build . gradle file:

While if you are a Maven user , add the following dependency to your pom . xml file:

Plus, add the Lombok dependency to the maven - compiler - plugin configuration section as follows :

Now, you have all you need to start using Lombok.

Most Common Lombok Annotations

Here you can find the most common and important Lombok annotations. Each of them will be explained and then seen in use compared to the equivalent Java vanilla translation. To see examples and get more support, click on each annotation and visit its page on the Lombok official documentation .

@Getter , @Setter

When a field is annotated with @Getter and/or @Setter , Lombok will automatically generate the default getter and/or setter, respectively. The default implementation for getters simply takes care of returning the annotated field. Similarly, the default implementation for setters takes one parameter of the same type as the annotated field and simply sets it with the received value. When a field called value is annotated with both @Getter and @Setter , Lombok will define a getValue ( ) (or isValue ( ) if the field is boolean ), and a setValue ( ) method. The generated getter/setter method will be public , unless a particular AccessLevel is specified. The allowed AccessLevel values are PUBLIC , PROTECTED , PACKAGE , and PRIVATE . Please, note that you can also annotate the entire class. In this case, this logic will be applied to each field.

With Lombok

Java vanilla, @noargsconstructor , @requiredargsconstructor , @allargsconstructor.

When a class is annotated with @NoArgsConstructor , Lombok will take care of automatically generating a constructor with no parameters. Likewise, when annotated with @AllArgsConstructor , a constructor with one parameter for each field in your class will be generated. Similarly, @RequiredArgsConstructor leads to a constructor with a parameter for each field requiring special handling. In particular, this involves non-initialized final fields, as well as any fields marked as @NonNull that are not initialized where declared. Please, do not forget that static fields will be ignored by these annotations.

When a class is annotated with @ToString , Lombok will take care of generating a proper implementation of the toString ( ) method. By default, a String containing the class name, followed by each field's value separated by a comma, will be returned. By setting the includeFieldNames parameter to true , the name of each field will be placed before its value. By default, all non-static fields will be considered when generating the toString ( ) method. Annotate a field with @ToString . Exclude to make Lombok ignore it. Alternatively, you can specify which fields you wish to be taken into account by using @ ToString ( onlyExplicitlyIncluded = true ) . Then, mark each field you want to include with @ToString . Include .

@EqualsAndHashCode

Annotate a class with @EqualsAndHashCode , and Lombok will automatically implement the equals ( ) and hashCode ( ) methods for you. By default, all non-static, non-transient fields will be taken into account. You can modify which fields are used by annotating them with @EqualsAndHashCode . Include or @EqualsAndHashCode . Exclude . Alternatively, you can annotate your class with @ EqualsAndHashCode ( onlyExplicitlyIncluded = true ) and then specify exactly which fields or methods you want to be used by marking them with @EqualsAndHashCode . Include . Please, note that the equals ( ) ) and hashCode ( ) ) methods will be generated by Lombok without breaking the contract between them. Follow the link on the two methods to the official Java documentation to learn more about the contracts that equals ( ) and hashCode ( ) implementations should fulfill.

You can annotate with @NonNull a record component, a parameter of a method, or an entire constructor. This way, Lombok will generate null-check statements for you accordingly.

@Data is a shortcut annotation that combines the features of @ToString , @EqualsAndHashCode , @Getter @Setter , and @RequiredArgsConstructor together. So, @Data generates all the boilerplate involved in POJOs ( Plain Old Java Objects ). This means, in particular, getters for all fields, setters for all non-final fields, proper toString , equals , and hashCode implementations involving every field of the class, and a constructor for all final fields.

@Value is the immutable variant of @Data . This means that all fields are made private and final by Lombok by default. Plus, setters will not be generated, and the class itself will be marked as final . This way, the class will not be inheritable. Just like what happens with @Data , toString ( ) , equals ( ) and hashCode ( ) implementations are also created.

Advanced Lombok Annotations

Here you can find the most complex Lombok annotations. Each of them will be explained and then seen in use compared to the equivalent Java vanilla translation. To see examples and get more support, click on each annotation and visit its page on the Lombok official documentation .

@Cleanup can be used to ensure a given resource is automatically cleaned up before leaving the current scope. By default, the cleanup method of the annotated resource is assumed to be close ( ) , but you can specify the name of the desired method to be called instead. Note that this annotation works by harnessing the try-with-resources statement .

@Synchronized

@Synchronized allows you to achieve something similar to the synchronized keyword, but locking on different objects. The keyword locks on this , while the annotation locks on a special private field named $lock . If this field does not exist, it will be created by Lombok. This is the default behavior, but you can also specify lock objects yourself. When dealing with static methods, the annotation will lock on a static field named $ LOCK . Please, consider that just like synchronized , the annotation can only be used on static and instance methods.

@SneakyThrows

@SneakyThrows can be used to sneakily throw checked exceptions without actually declaring them in your method's throws clause, as you normally would. So, this annotation allows you to avoid the required try - catch blocks completely by handling all the checked exceptions quietly. Lombok will not ignore, wrap, replace, or modify the thrown checked exception. On the contrary, it will mislead the compiler. In fact, at the JVM ( Java Virtual Machine ) class file level, all exceptions can be thrown regardless of the throws clause of your methods, which is why this works. This annotation can be dangerous and should be used carefully. This is why you should read this page from the Lombok official documentation to learn more about when and how to use it.

You may need to develop a builder object allowing you to create objects by following a step-by-step construction pattern, such as Author . builder ( ) . id ( "1" ) . name ( "Maria" ) . surname ( "Williams" ) . build ( ) ; . This is particularly useful when dealing with large classes with several fields. Instead of using a constructor with many parameters, you can use this more readable approach. By using the @Builder annotation, you let Lombok generate the builders for you. By annotating a class with @Builder , Lombok will produce a class implementing the aforementioned builder pattern. For example, by annotating the Author class, an AuthorBuilder class will be automatically generated. Since the behavior of your builder may be complex or highly-tailored, Lombok offers many parameters to achieve the desired result. You can find out them all here .

The majority of loggers require you to set up a logger instance in every class where you want to log. This definitely involves boilerplate code. By annotating a class with @Log , Lombok will automatically add a static final log field, initialized as required by your logging library. This is why Lombok provides developers with an annotation per each of the most popular logging frameworks. You can find the entire list here .

The Lombok Plugin

The most popular and widely used IDEs come with an official Lombok plugin designed to help developers use Lombok. In particular, it supports you by offering shortcuts to the most common Lombok annotation. Plus, it suggests to you the annotations you may require or be looking for based on where you clicked. At the time of writing IntelliJ IDEA , Eclipse, Spring Tool Suite, (Red Hat) JBoss Developer Studio, MyEclipse , Microsoft Visual Studio Code , and Netbeans are officially supported. Follow the link related to your IDE to get support on how to install it. Visit the Lombok website for the complete list of all supported IDEs.

Is Using Lombok A Risk?

You may be concerned about spreading Lombok annotations throughout your codebase. In fact, what would happen if you decided to avoid using it? You might be finding yourself stuck. Well, this is not a real problem because Lombok comes with a delombok tool. As stated in the official documentation , although not covering all possible IDEs and cases, it makes the process of freeing your code from Lombok easier. What this tool does is auto-generate Java source code containing the same features contained in the bytecode Lombok would have injected. This way, your Lombok annotated codebase will be simply replaced with a standard, non-Lombok Java one. As a result, your entire project will no longer depend on Lombok. So, to answer the original question, no, not at all. Using Lombok does not represent a risk for the future or your project.

In this article, we looked at how to use Project Lombok, a Java library that automatically plugs into your editor and builds tools, to avoid writing boilerplate, boring, and repetitive code Java is well known for. As shown, this is an easy way to make you a more productive developer and do not waste your time on cumbersome activities. By starting to take advantage of its most relevant annotations, you can avoid writing thousand of lines of code with no real value from the business logic point of view of your project. Plus, there is always the possibility to make your project no longer depend on Project Lombok easily. So, it using it does not represent a risk of finding yourself locked in. In conclusion, every Java developer should use Project Lombok, and explaining everything you need to start using it is what this article was aimed at.

Thanks for reading! I hope that you found this article helpful. Feel free to reach out to me with any questions, comments, or suggestions.

Java Guides

Java Guides

Search this blog, project lombok annotations with examples.

Java, while being a powerful and versatile language, often comes with a side of verbosity. Boilerplate code can often overshadow the business logic, making the code harder to read and maintain. Project Lombok is an initiative that aims to counter this by introducing a set of annotations to help minimize this boilerplate. In this post, we will explore some of the popular Lombok annotations, understand their purpose, see examples, and enumerate the benefits.

1. @Getter and @Setter 

Instead of manually writing getters and setters for each field in your class, you can use Lombok's  @Getter  and  @Setter  annotations. 

Example without Lombok: 

With Lombok:

  • Reduces lines of code. 
  • Auto-generated code ensures fewer human errors. 
  • Makes the class more readable.

2. @NoArgsConstructor 

3. @allargsconstructor ,  4. @requiredargsconstructor .

  • Eliminates the need to manually create constructors. 
  • Ensures consistency as fields are added or removed. 
  • Enhances code readability by reducing boilerplate.

@Data annotation is a shortcut for @ToString, @EqualsAndHashCode, @Getter on all fields, and @Setter on all non-final fields, and @RequiredArgsConstructor! 

  • Complete boilerplate code reduction for standard class methods.
  • A one-stop annotation for common requirements.

This annotation creates and injects a logger into your class. 

  • No need to manually define the logger.
  • Simplifies logging code.

7. @Builder 

Implement the Builder pattern without coding the boilerplate. 

  • Fluent API style initialization.
  • Reduces complexity in classes with many parameters.

Post a Comment

Leave Comment

My Top and Bestseller Udemy Courses

  • Spring 6 and Spring Boot 3 for Beginners (Includes Projects)
  • Building Real-Time REST APIs with Spring Boot
  • Building Microservices with Spring Boot and Spring Cloud
  • Full-Stack Java Development with Spring Boot 3 & React
  • Testing Spring Boot Application with JUnit and Mockito
  • Master Spring Data JPA with Hibernate
  • Spring Boot Thymeleaf Real-Time Web Application - Blog App

Check out all my Udemy courses and updates: Udemy Courses - Ramesh Fadatare

Copyright © 2018 - 2025 Java Guides All rights reversed | Privacy Policy | Contact | About Me | YouTube | GitHub

list of all lombok annotations

Website logo

Join Over 10 000 Subscribers

Signup for our weekly newsletter to get the latest updates

Introduction to Lombok Data Annotation

• Azhrioun Abderrahim • Jan 16, 2022 • lombok • 11 mins read

As a developer, I couldn’t imagine myself programming Java classes without using lombok data annotation .

So, in this article, I will try to highlight the importance of the lombok project and cover in-depth every point related to @Data annotation.

Stay tuned,

@Data Annotation Overview

Using lombok @Data can surely provide significant technical benefits to our Java projects. It reduces the required extra code that usually brings no real value to the business side of our applications.

So, let’s see this annotation in detail.

What is Lombok Data Annotation?

In short, @Data is a special annotation provided by the lombok project. Its main purpose is to automatically generate all the extra code that is frequently associated with POJOs and Java beans.

You may wonder what is boilerplate code. Well, it is the repetitive code that we have to write each time such as:

Getter methods for all fields

Setter methods for all fields

toString() method

equals() and hashCode() implementations

Constructor that initializes all final fields

The lombok project comes with a host of ready-to-use annotations. However @Data is very special because it provides an implicit shortcut that binds together all the following annotations:

@RequiredArgsConstructor

@EqualsAndHashCode

Please bear in mind that each annotation has one specific purpose, we should use it only when it makes sense.

For example, we use the @ToString annotation only when we want to implement the toString method.

How Lombok @Data Works?

Lombok hooks itself into the compilation phase and acts as an annotation processor that generates the extra code we need for our classes.

Its real job is not to generate new files but to modify the existing ones.

By annotating a particular class with @Data , we tell lombok to generate:

Parameterized constructor for required fields

Setters and getters

equals , hashCode and toString methods

And all that silently during compile time. Awesome, right?

Now that we know how lombok works, let’s see how to add it in eclipse.

Install Lombok in Eclipse IDE

To work with lombok plugin, we need to configure it first. Follow the below steps to add it in eclipse (Windows OS):

Download the jar file from https://projectlombok.org/download

Go to the jar file location, then execute it or run this command line in your terminal: java -jar lombok.jar

Once the Lombok window is opened, specify the eclipse.exe location under the Eclipse installation folder

Click on Install/Update button to start the installation process

Install Lombok Plugin in Eclipse

If you are a big fan of Maven like me, you need just to add the following dependency in the pom.xml of your project:

Feel free to check our articles on how to install maven:

Install maven on windows 10

Install maven on mac os

Example Without @Data

Let’s see how to create a POJO class in Java without using any lombok annotations. For instance, consider the Person class:

As we can see, we have already more than 100 lines of code for a class with 5 properties .

Person class has just 5 properties, so it is normally a basic simple Java class. However, with the extra code of the getters and setters … we ended up with a quite overwhelming boilerplate zero-value code.

You may say that most Java IDE can also auto-generate getters and setters (and even more) for us with just a few clicks.

Yes, you are right. However, the generated code needs to live in your sources and must be maintainable and maintained.

Example with Lombok @Data

With this annotation, we will be able to focus only on what is important in our class: its data and its representation.

The rest will be generated automatically by lombok. Thanks to the Data annotation.

Now, let’s take a close look at our class Person decorated with @Data :

And that’s how we can go from more than 100 lines of code to just 9 lines . Cool, right?

The code is more clearer and concise that way. As shown above, there is less code to write and maintain. Lombok does not stop here, it can provide more flexibility and readability to our code.

Lombok @Data example

Please keep in mind that @Data annotation is like having the following implicit annotations:

Now, let’s verify if @Data annotation did its job and that everything works as excepeted:

Static Factory Method Using @Data Annotation

With some adjustments added to our previous example, we can end up with a class that can only be instantiated through a static factory method .

With the help of the staticConstructor attribute, we can tell @Data to generate a private constructor and a public static factory method:

The name of the static method is “of” . Here the “of” convention is considered a best practice because it is heavily used in the new Java 8 APIs.

That way, we can create our instances using Person.of() instead of new Person() .

Please keep in mind that we can also use the old naming conventions such as newInstance .

Use @Data with Other Annotations

The best thing about the data annotation is its flexibility as it can be used alongside other annotations.

For example, we can use @Data with @Setter(AccessLevel.NONE) to make our class read-only. We can use it also with @AllArgsConstructor to generate an all-args constructor instead of the default required args constructor.

Let’s see how we can use data annotation with @ToString to tell lombok to skip the field names in the implementation of the toString() method:

includeFieldNames=false simply informs @ToString to omit each field name and display a comma-separated list of all the field values:

Exclude Fields with @Data

By default, @Data includes all the fields when generating getters, setters, and other implementations.

Unfortunately, it does not offer direct support for ignoring and excluding some specific fields.

Though all hope is not lost, we can combine @Data with other lombok specific annotations to address our central question:

As shown above, we can use the Exclude parameter to ignore and skip the annotated fields.

Lombok @Data With @Builder

As we have already mentioned in the beginning, @Data generates a required-args constructor.

However, this behavior will change if we add @Builder to the equation.

Using @Data and @Builder annotations together will generate an all-args constructor instead.

The problem here is that most DI Frameworks such as Spring rely on a no-args constructor to initialize objects.

So, a nice workaround to fix this issue would be using the @NoArgsConstructor annotation to generate the default constructor for us.

Lombok will complain if we use @NoArgsConstructor alongside with @Data and @Builder , that’s why we need to add @AllArgsConstructor too.

Difference Between @Value and @Data

The big difference between @Value and @Data annotation is that @Value is mainly used to create immutable objects .

@Value is a also an all-in-one annotation that combines: @Getter, @AllArgsConstructor , @ToString and @EqualsAndHashCode and @FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE) .

As we can see @Value , unlike the Data annotation, does not contain @Setter annotation. Omitting setters is the first step for promoting immutability.

@FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE) allows to mark the fields as private and final.

The Expanded version of the @Value annotation looks like bellow:

If we de-lombok our class Student , we will get:

That’s all. In this article, we explained in detail what is lombok @Data annotation and how we can use it in our Java projects.

Along the way, we have showcased how to use it with @Builder and explained the core difference between it and the @Value annotation.

I hope you have found this article helpful, enlightening and inspiring to convince you to give lombok a chance to get into your Java development toolset.

Liked the Article? Share it on Social media!

Lombok技术揭秘 _ 自动生成带代码的幕后机制

作者头像

1. Lombok简介

  • 1.1 Lombok是什么
  • Project Lombok 是一个 JAVA 库,它可以自动插入编辑器和构建工具,为您的 JAVA 锦上添花。
  • 再也不要写另一个 getter/setter 或 equals 等方法,只要有一个注注解,你的类就有一个功能齐全的生成器,自动记录变量,等等。
  • 1.2 Lombck相关注解功能介绍

2. Lombok原理介绍

  • 2.1 Java类文件编译过程

首先,我们知道 Lombok 功能是作用在类编译时期,那我们来看下一个类编译的过程。

  • 定义一个 PersonDTO.Java 类
  • Javac PersonDTO.Java 对源代码进行解析转化,会生成一棵抽象语法树( AST );
  • 运行过程中会调用实现了 JSR 269 注解处理器,下面介绍;
  • JSR 实现可处理自定义逻辑,包括可修改编译后的抽象语法树(AST);
  • Javac 使用修改后的抽象语法树(AST)生成字节码文件;

list of all lombok annotations

AST 是抽象语法树(Abstract Syntax Tree) 的缩写,是 JAVA 源代码展示的一种树状结构它将代码的结构和语法元素映射到树节点上,使得程序可以在编译、

分析和转换过程中更容易地操作和理解。有兴趣可以学习 JavaParser 源码, 了解将 Java 源代码解析生成成一个抽象语法树( AST ),这个树形结构表示了代码的

语法结构包括类、方法、变量、语句等等过程。

github地址:https://github.com/javaparser/javaparser.

如: PersonDTO.Java 在 idea 中使用可视化工具展示文件 AST 树

list of all lombok annotations

  • 2.2 JSR 269介绍

首先 JSR 269全称" Pluggable Annotation Processing API ",是 JAVA 平台的一项规范,也被称之为注解处理器 API 。在Java6引入,用于在编译时处理

注解,目标是提供更丰富的编译时元数据处理能力,以增强Java编译器的功能。这个规范允许开发人员创建自定义的注解处理器,这些处理器可以在编译时检查、

分析和生成Java代码。

  • Servlet、JAX-RS(RESTful Web服务)JSR 269 来生成用于处理 HTTP 请求的代码。
  • Spring Boot 项目中以处理各种自定义注解,如 @Controller、@Service、@Repository 等。这些注解可以用于自动化配置、依赖注入等方面。
  • Hibernate 它使用 JSR 269 来处理 JPA 注解,并生成与数据库交互的代码。
  • Lombok 是一个 JAVA 库,它通过注解处理器生成常见的 JAVA 代码,如 getter、setter、equals、hashCode 等,以简化开发工作。
  • MapStruct 是一个用于对象映射的 JAVA 库,它使用 JSR 269 来生成类型安全的映射代码,帮助开发人员将一个对象映射到另一个对象。

如何实现自定义注解注解处理器:

1.声明自定义注解;如 Lombok 下的 @Data,@Getter,@Setter等。

2.实现 Process接口,或者继承 AbstractProcessor 复写 process 方法,处理自定义注解逻辑。

  • Resource 文件:项目 META-INF/services 创建 javax.annotation.processing.Processor 文件,自定义注解处理器的全类名写到此文件中。
  • 通过谷歌工具包 auto-service ,可自动生成以上配置文件。
  • 2.3 Lombok 实现原理

1. Lombok 实际就是结合注解处理器和 AST 技术, Lombok 实现的注解处理器会遍历 AST ,查找与 Lombok 注解相关的元素,根据注解的要求生成新的代码。

list of all lombok annotations

2.编译前后的 AST 语法树对比

list of all lombok annotations

加入@Getter注解编译后

list of all lombok annotations

3. Lombok 注解处理器,采用 Resource 方式注册编译注解处理器

list of all lombok annotations

注解处理器 AnnotationProcessor 源码:

自定义注解处理器 Handler : 在 Jar 包的 lombok.javac.handlers下,每个注解处理对应一个 Handler. 如 HadlerGetter.java 操作 AST 树生成 getter 方法.

list of all lombok annotations

2.4手动实现一个 @Getter 功能

  • 2.4.1.创建 maven 工程 demo 包含两个子模块 getter/getter-use

list of all lombok annotations

  • 2.4.2. getter 工程

自定义 GetterTest 注解

GetterTest 编译注解处理器 GetterProcessor

  • 2.4.4 getter-use工程

pom 文件 引入getter工程

PersonDTO 使用@GetterTest

  • 2.5.5 项目进行编译

getter 模块下自动生成注册器

list of all lombok annotations

getter-use 模块下 PersonDTO.class 可见生成了对应属性的 get 方法

list of all lombok annotations

本文通过以上对 Lombok 相关介绍,通过对 JAVA 文件编译过程分析和 JSR269 实现的方式, 基于这个规范然后引申出 Lombok 实现原理过程介绍,以及手动实现 getter 案例,想必我们对 Lombok 原理也有了相应的了解。虽然 Lombok 提供了许多便利,由于生成的代码不在源文件中可见,就会导致代码的可读性和维护性较差。在工作中 Lombok 使用时注意闭坑:

Lombok 官网地址: https://projectlombok.org

JavaParser 源码地址: https://github.com/javaparser/javaparser

JAVA 抽象语法树 AST 浅析与使用: https://www.freesion.com/article/4068581927/

本文分享自 政采云技术 微信公众号, 前往查看

如有侵权,请联系 [email protected] 删除。

本文参与  腾讯云自媒体分享计划   ,欢迎热爱写作的你一起参与!

 alt=

Copyright © 2013 - 2024 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有 

深圳市腾讯计算机系统有限公司 ICP备案/许可证号: 粤B2-20090059  深公网安备号 44030502008569

腾讯云计算(北京)有限责任公司 京ICP证150476号 |   京ICP备11018762号 | 京公网安备号11010802020287

Copyright © 2013 - 2024 Tencent Cloud.

All Rights Reserved. 腾讯云 版权所有

  • Experimental
  • Discuss / Help
  • Documentation for contributors
  • Contact the team behind Project Lombok
  • Order / Donate
  • Build tools
  • IntelliJ IDEA
  • Spring Tool Suite
  • JBoss Developer Studio
  • Visual Studio Code

or: How I learned to stop worrying and love the NullPointerException.

You can use @NonNull on a record component, or a parameter of a method or constructor. This will cause to lombok generate a null-check statement for you.

Lombok has always treated various annotations generally named @NonNull on a field as a signal to generate a null-check if lombok generates an entire method or constructor for you, via for example @Data . However, using lombok's own @lombok.NonNull on a parameter or record component results in the insertion of the null-check at the top of that method.

The null-check looks like if (param == null) throw new NullPointerException("param is marked non-null but is null"); and will be inserted at the very top of your method. For constructors, the null-check will be inserted immediately following any explicit this() or super() calls. For record components, the null-check will be inserted in the 'compact constructor' (the one that has no argument list at all), which will be generated if you have no constructor. If you have written out the record constructor in long form (with parameters matching your components exactly), then nothing happens - you'd have to annotate the parameters of this long-form constructor instead.

If a null-check is already present at the top, no additional null-check will be generated.

With Lombok

Vanilla java, supported configuration keys:, small print.

Lombok's detection scheme for already existing null-checks consists of scanning for if statements or assert statements that look just like lombok's own. Any 'throws' statement as the 'then' part of the if statement, whether in braces or not, counts. Any invocation to any method named requireNonNull or checkNotNull counts. The conditional of the if statement must look exactly like PARAMNAME == null ; the assert statement must look exactly like PARAMNAME != null . The invocation to a requireNonNull -style method must be on its own (a statement which just invokes that method), or must be the expression of an assignment or variable declaration statement. The first statement in your method that is not such a null-check stops the process of inspecting for null-checks.

While @Data and other method-generating lombok annotations will trigger on various well-known annotations that signify the field must never be @NonNull , this feature only triggers on lombok's own @NonNull annotation from the lombok package.

A @NonNull on a primitive parameter results in a warning. No null-check will be generated.

A @NonNull on a parameter of an abstract method used to generate a warning; starting with version 1.16.8, this is no longer the case, to acknowledge the notion that @NonNull also has a documentary role. For the same reason, you can annotate a method as @NonNull ; this is allowed, generates no warning, and does not generate any code.

IMAGES

  1. list of lombok annotations

    list of all lombok annotations

  2. Lombok @Value annotation Example

    list of all lombok annotations

  3. How To Reduce Boilerplate Code In Java Using Lombok Annotations

    list of all lombok annotations

  4. list of lombok annotations

    list of all lombok annotations

  5. Lombok Annotations. Spice up your Java + Spring

    list of all lombok annotations

  6. Lombok Annotations in Spring Boot

    list of all lombok annotations

VIDEO

  1. Lombok para que serve

  2. List of TestNG Annotations

  3. Lombok #shortsfeed #shorts

  4. [Utils v1] Lombok

  5. Fall of Bali Kingdom of Mataram's Gameplay

  6. List two different annotations present in TestNG but not in JUnit (Selenium Interview Question #507)

COMMENTS

  1. The Ultimate Lombok Annotations Guide

    Method level Annotations @Synchronized. The @Synchronized annotation is a method level annotation. According to Lombok, using this annotation is preferred over using Java's synchronized keyword because unlike the synchronized keyword which locks on this, the annotation will synchronize the method on an inner variable.If the annotation is added to a static method, then it will lock on a ...

  2. All the 16 Lombok Annotations Explained in a 4-minute article

    We can add an annotation at the class level and Lombok will create a log instance for us. Depending on what logging library we use, there are different implementations available, some popular ones ...

  3. A Complete Guide to Lombok

    This is the list of all the prerequisites to replicate the examples that will be shown next: Java >= 1.8; Gradle >= 4.x or Maven 3.6.x; Project Lombok >= 1.18.20; What is Lombok. Project Lombok (from now on, Lombok) is an annotation-based Java library that allows you to reduce boilerplate code. Lombok offers various annotations aimed at ...

  4. Introduction to Project Lombok

    Project Lombok is a library that simplifies Java code by reducing boilerplates, enhancing readability, and improving performance. In this article, you will learn how to use Lombok's annotations, such as @Getter, @Setter, @Data, @AllArgsConstructor, and @NoArgsConstructor, to automate common tasks and avoid writing repetitive code. You will also see how Lombok integrates with IDEs and tools ...

  5. Lombok Using @With Annotations

    3. Requirements. To use the @With annotation correctly, we need to provide an all-arguments constructor. As we can see from the above example, the generated method requires this to create a clone of the original object. We can use either Lombok's own @AllArgsConstructor or @Value annotation to satisfy this requirement.

  6. Complete Guide to Lombok Constructor Annotations

    Overview. Lombok project has taken constructors generation to the next level by providing a list of handy ready-to-use annotations: @AllArgsConstructor, @NoArgsConstructor, and @RequiredArgsConstructor. Despite the fact that all of them can be used to generate the boilerplate code required to create constructors, they are quite different.

  7. Project Lombok Annotations with Examples

    In this article, we will discuss all the Project Lombok annotations with an example. Lombok is a library used for reducing the boilerplate code from Java source code. Boilerplate code is a typical source code that cannot be omitted by the language specification. Basically, the boilerplate code does not have a specific logic hence it becomes redundant code in implementation.

  8. Stable

    Delombok copies your source files to another directory, replacing all lombok annotations with their desugared form. So, it'll turn @Getter back into the actual getter. It then removes the annotation. This is useful for all sorts of reasons; you can check out what's happening under the hood, if the unthinkable happens and you want to stop using ...

  9. Lombok Annotations: Simplifying Java Development and Boosting ...

    Some of the most popular Lombok annotations are: @Data: This annotation generates getters, setters, hashCode, equals, and toString methods for all fields in a class.

  10. Guide to Lombok With Spring Boot

    So use Lombok wisely, according to your requirements. 2. @NoArgsConstructor and @AllArgsConstructor. Constructor is a special method that is used to initialize objects. Lombok provides three annotations to create a constructor, but two of them are popular ones. @NoArgsConstructor generates a default constructor with no parameters.

  11. @Data

    Overview. @Data is a convenient shortcut annotation that bundles the features of @ToString, @EqualsAndHashCode, @Getter / @Setter and @RequiredArgsConstructor together: In other words, @Data generates all the boilerplate that is normally associated with simple POJOs (Plain Old Java Objects) and beans: getters for all fields, setters for all non ...

  12. @NoArgsConstructor, @RequiredArgsConstructor, @AllArgsConstructor

    Lombok will copy any of these annotations from the field to the constructor parameter, the setter parameter, and the getter method. Note that lombok ships with a bunch of annotations 'out of the box' which are known to be copyable: All popular nullable/nonnull annotations. lombok.noArgsConstructor.extraPrivate = [true | false] (default: false)

  13. Introduction to Lombok Data Annotation

    Go to the jar file location, then execute it or run this command line in your terminal: java -jar lombok.jar. Once the Lombok window is opened, specify the eclipse.exe location under the Eclipse installation folder. Click on Install/Update button to start the installation process.

  14. Using the @Singular Annotation with Lombok Builders

    1. Overview. The Lombok library provides a great way of simplifying data objects. One of the key features of Project Lombok is the @Builder annotation, which automatically creates Builder classes for creating immutable objects. However, populating collections in our objects can be clumsy with the standard Lombok-generated Builder classes.

  15. Lombok Deep Dive: Exploring Lesser-Used Lombok Annotations

    While many Java developers are familiar with Lombok's popular annotations like @Getter, @Setter, and @ToString, there exists a treasure trove of lesser-known annotations that can further ...

  16. @Log (and friends)

    The various @Log variants were added in lombok v0.10.NEW in lombok 0.10: You can annotate any class with a log annotation to let lombok generate a logger field. The logger is named log and the field's type depends on which logger you have selected.. NEW in lombok v1.16.24: Addition of google's FluentLogger (via @Flogger). NEW in lombok v1.18.10: Addition of @CustomLog which lets you add any ...

  17. Lombok @Builder with Examples- HowToDoInJava

    Ensure you have included Lombok in the project and installed Lombok support in the IDE. If we want to marshal or unmarshal the builder classes with Jackson then we should be using the @Jacksonized annotation. 1. @Builder. The @Builder annotation produces complex builder APIs for the annotated POJO classes. For example, if we annotate a class ...

  18. Lombok's @ToString Annotation

    Overview. As we know, the toString () method is used to get the string representation of a Java object. Project Lombok can help us generate consistent string representations without the boilerplate and cluttering the source code. It can also improve maintainability, especially where classes might contain a large number of fields.

  19. @Getter and @Setter

    lombok.copyableAnnotations = [A list of fully qualified types] (default: empty list) Lombok will copy any of these annotations from the field to the setter parameter, and to the getter method. Note that lombok ships with a bunch of annotations 'out of the box' which are known to be copyable: All popular nullable/nonnull annotations.

  20. Lombok技术揭秘 _ 自动生成带代码的幕后机制

    Lombok 是一个 JAVA 库,它通过注解处理器生成常见的 JAVA 代码,如 getter、setter、equals、hashCode 等,以简化开发工作。. MapStruct 是一个用于对象映射的 JAVA 库,它使用 JSR 269 来生成类型安全的映射代码,帮助开发人员将一个对象映射到另一个对象。. 1.声明自定义 ...

  21. Implementing a Custom Lombok Annotation

    In this tutorial, we'll implement a custom annotation using Lombok to remove the boiler-plate around implementing Singletons in an application. Lombok is a powerful Java library that aims to reduce the boiler-plate code in Java. If you're not familiar with it, here you can find the introduction to all the features of Lombok.. An important note: Lombok 1.14.8 is the latest compatible ...

  22. @With

    lombok.accessors.prefix += a field prefix (default: empty list) This is a list property; entries can be added with the += operator. Inherited prefixes from parent config files can be removed with the -= operator. Lombok will strip any matching field prefix from the name of a field in order to determine the name of the getter/setter to generate.

  23. Using Lombok's @Builder Annotation

    The first and only step is to add the annotation to the class declaration: @Getter @Builder public class Widget {. private final String name; private final int id; } Lombok does all the work for us. We can now build a Widget and test it: Widget testWidget = Widget.builder() .name( "foo" )

  24. @NonNull

    Lombok has always treated various annotations generally named @NonNull on a field as a signal to generate a null-check if lombok generates an entire method or constructor for you, via for example @Data. However, using lombok's own @lombok.NonNull on a parameter or record component results in the insertion of the null-check at the top of that ...