39. Project Lombok in Java in depth | Lombok top 10 features
Estimated read time: 1:20
Learn to use AI like a Pro
Get the latest AI workflows to boost your productivity and business performance, delivered weekly by expert consultants. Enjoy step-by-step guides, weekly Q&A sessions, and full access to our AI workflow archive.
Summary
This in-depth video by Shrayansh under 'Concept && Coding' explains Project Lombok, a popular Java library designed to reduce boilerplate code using annotations. Lombok processes annotations during compilation to inject code into Java classes. The video covers its compatibility with Java versions starting from Java 6, and highlights how it simplifies code by introducing new features such as 'val' and 'var' for local variable declarations, '@NonNull', 'getter and setter' annotations, '@ToString', and 'equals and hashcode' methods, among others. Shrayansh also illustrates the usage of Lombok in IntelliJ, addressing common issues programmers might face, such as the necessity of the plugin and enabling annotation processing, to integrate Lombok seamlessly into their development workflow.
Highlights
Shrayansh introduces Project Lombok, explaining its role in reducing Java boilerplate with ease. 💡
The Lombok library becomes indispensable by simplifying local variable declarations with 'val' and 'var'. 🎉
IntelliJ's red underline problem? Solved with Lombok's plugin and annotation processing settings! 🔍
Lombok offers key annotations: '@Getter', '@Setter', and '@ToString', standardizing common methods. 📜
Immerse in advanced features like '@Data' and '@Builder', enhancing code structure and efficiency. 🏗️
Key Takeaways
Project Lombok is a lifesaver for Java developers, reducing boilerplate code with annotations. 🚀
By using Lombok, you save time on writing repetitive code, making your coding life easier! ⏰
Lombok integrates well with Java from version 6 onwards, ensuring compatibility with modern projects. 📈
To fully leverage Lombok in your IDE, ensure you install the plugin and enable annotation processing. 🛠️
The video covers the top 10 features of Lombok, which are invaluable for efficient Java coding. ✨
Overview
In the video 'Project Lombok in Java in depth', Shrayansh from 'Concept && Coding' takes viewers on an enlightening journey through Lombok, a Java library that significantly reduces boilerplate code using annotations. The discussion kicks off with an introduction to Lombok's functionality and its widespread use in the industry, emphasizing how it processes annotations during compilation to inject necessary code into Java classes, simplifying developer workflows immensely.
Further into the video, Shrayansh elaborates on the installation and integration of Lombok with popular Integrated Development Environments (IDEs), particularly IntelliJ. He addresses potential compilation issues and outlines steps to enable annotation processing, ensuring a seamless integration for developers. This section is pivotal for those looking to fully harness the power of Lombok in their Java projects, especially considering its full compatibility with Java versions 6 and above.
The latter part of the video dives into ten prominent Lombok features like '@NonNull', '@Getter', '@Setter', '@ToString', and more, each enhancing Java coding practices. Through detailed examples, Shrayansh illustrates the benefits Lombok brings to the table, making it not just a time-saver but a standard for efficient Java programming. Whether you're dealing with local variables using 'val' or implementing complex patterns with '@Builder', Lombok streamlines these tasks, underscoring why it's a developer favorite.
Chapters
00:00 - 00:30: Introduction to Project Lombok The chapter 'Introduction to Project Lombok' begins with Shant welcoming viewers to the concept encoding series. Shant mentions that while most Java concepts have been covered, there are new features in the latest Java version that will be addressed. Additionally, there will be a focus on older Java features that were not previously covered. The chapter specifically aims to introduce Project Lombok as the starting topic.
00:30 - 01:00: What is Lombok? The chapter introduces Lombok, a widely used Java library that helps reduce boilerplate code through annotations. It explains how Lombok processes annotations during compilation and injects code into Java classes, addressing a common complaint among Java developers about writing excessive, unnecessary code.
01:30 - 03:00: How Lombok Works with IntelliJ This chapter introduces the purpose and functionality of Lombok in conjunction with IntelliJ. It highlights the main goal of Lombok, which is to reduce boilerplate code apart from business logic, making code more succinct and readable. Lombok is compatible with Java versions starting from Java 6 and supports all later versions. For developers working in the industry, Lombok can be incredibly beneficial, offering features that streamline coding processes. To begin using Lombok in a project, the first step involves adding the Lombok library to the project's pom.xml file.
04:30 - 05:00: Top Lombok Features Overview This chapter provides an overview of Lombok's key features, demonstrating how even when the IDE highlights a compilation error, the code can still run successfully and produce the expected output. The example focuses on integrating the latest Lombok version into a Maven project and showcases a particular feature of Lombok that seems to trigger IDE warnings but works without issues during runtime.
05:00 - 06:30: Feature 1: var and val ### Chapter: Feature 1: var and val
In this chapter, the discussion revolves around the Kotlin language features, specifically 'var' and 'val'. The dialogue begins with a query about a compilation error despite the code working fine. The explanation provided attributes this to Lombok, a Java library tool used to reduce boilerplate code with annotations. Lombok injects code during compilation, which might not be visible in the IDE initially, causing some confusion. The main focus is on understanding this process and correctly using 'var' (a mutable variable) and 'val' (an immutable variable) in Kotlin.
06:30 - 08:20: Feature 2: @NonNull In this chapter, the focus is on the use of the @NonNull feature from the Lombok library. The discussion highlights how IDEs, such as IntelliJ, may initially show compilation errors when this feature is used, as the IDE might not recognize it without the necessary dependencies. However, by adding the Lombok dependency to the project, these errors are resolved during the compilation phase. The chapter emphasizes understanding the configuration and setup needed to utilize Lombok features effectively.
08:20 - 13:00: Feature 3: Getter and Setter Annotations This chapter discusses the use of getter and setter annotations in Java development, focusing on the Lombok library. It highlights the necessity of adding the Lombok plugin to your Integrated Development Environment (IDE) to properly handle these annotations. Specifically, it addresses the need for the plugin to correctly interpret data types from .class files to strings, which might otherwise be misunderstood by the IDE.
13:00 - 18:30: Feature 4: @ToString The chapter discusses the @ToString feature in Lombok. It highlights the necessity of enabling specific settings in your Integrated Development Environment (IDE) for proper functionality. These settings include Build, Execution, and Deployment along with Annotation Processing. By enabling these features, the IDE can accurately simulate what Lombok performs during compile time. This is demonstrated by the absence of errors in the IDE after configuring these settings.
18:30 - 24:30: Feature 5: Constructors Annotations The chapter discusses the role of Lombok constructors annotations in a development environment. It emphasizes how Lombok operates during compilation to manage constructor annotations and enhance coding efficiency. Additionally, it points out that while certain setups like adding to the pom.xml aren't mandatory, they are beneficial, especially enabling annotation processing in the Integrated Development Environment (IDE). This allows the IDE to be aware of Lombok features which aids in coding.
24:30 - 30:00: Feature 6: Equals and HashCode The chapter titled 'Feature 6: Equals and HashCode' is part of a broader discussion on Lombok, a Java library that provides automatic generation of boilerplate code. The speaker intends to cover 10 frequently used Lombok features, although a comprehensive list is available online. This particular section is likely focused on explaining the 'Equals and HashCode' feature, which are crucial methods in Java for comparing objects and ensuring proper functioning of collections like HashSet or HashMap. However, the transcript indicates an interruption or incompletion in the topic discussion.
30:00 - 35:30: Feature 7: @Data The chapter titled 'Feature 7: @Data' delves into the concept of determining the type of local variable declarations through initializer expressions. It emphasizes the importance of local variables and explains that the type of a variable is inferred from the initializer expression. The chapter uses an example of using a variable name with an expression to demonstrate how the type is determined.
35:30 - 40:30: Feature 8: @Value The chapter titled 'Feature 8: @Value' explains the concept of local variables being marked as immutable using some feature or annotation. The annotation, referred to as 'well' or '@Value,' can only be applied to local variables within a block of code, not on fields or parameters. The transcript emphasizes that this feature does not apply outside of local variable scope, highlighting its restriction to making local variables immutable.
40:30 - 44:00: Feature 9: Builder Pattern with @Builder The chapter discusses the difference between 'final' variables and regular variables in the context of using the Builder pattern with the @Builder annotation. A specific example is given where a variable 'a' is declared as 'final', preventing its value from being changed, which results in an error message: 'cannot assign a value to final variable'. The chapter emphasizes understanding these concepts in Java programming to effectively utilize the Builder design pattern.
44:00 - 48:00: Feature 10: @Cleanup The chapter discusses the '@Cleanup' feature, emphasizing its utility in managing resources. It indicates that using 'well' makes a local variable immutable, unlike 'where', which doesn't enforce immutability, allowing value changes. The discussion also highlights the automatic type determination based on initialization expression, eliminating concerns about specifying variable types like int, string, or object. This is identified as the first feature in a sequence of features being discussed.
48:00 - 48:00: Conclusion and Closing The chapter 'Conclusion and Closing' explains the usage of the @Nonnull annotation in Java. This annotation helps in generating a null check statement automatically, which throws a NullPointerException if the passed value is null. It is particularly used on method or constructor parameters to ensure that they aren't null. An example is provided where a method is annotated with @Nonnull and uses system.out.println. The explanation seems to be cut off before completion.
39. Project Lombok in Java in depth | Lombok top 10 features Transcription
00:00 - 00:30 Shant this side welcome to concept encoding and in Java we have almost covered everything but there are certain features which has been added into the latest version of Java. So from now on I will try to cover those features which has been introduced newly plus also some uh features which were there in the older version of the Java which we have not covered. So I would also like to cover those also. So I want to start with this Lombok first right because
00:30 - 01:00 this is very popular and highly used in the industry. So what is Lombok? It's a Java library which help to reduce the boiler code using annotations. So during compilation it process the annotation and inject code into our Java classes. So if you talk with any of the engineer who is not working with Java, the first thing they will say that hey in Java we have to write too much code unnecessary code
01:00 - 01:30 right that is nothing but a boilerplate code code apart from business logic. So you can say that this project is just an initiative to reduce those boiler code and this Lombok feature is compatible with Java starting from Java 6 and supports all later version and if you are working in the industry you might see lot of features in your project. So first thing first we have to add the library in our pom.xml. So just pick the
01:30 - 02:00 latest Lombong version and add it into your pom.xml. Now see before I go and tell you what is this just see this example where I'm using one of the feature of the Lombok but my IntelliJ is showing me the red line right means it's some kind of a compilation error it is showing but when I try to run it it runs properly and printed
02:00 - 02:30 hello how come my intelligent is showing compilation error but it is working fine. It's because Lombok will add the code during compile time. I told you right. So Lombok is like we use certain Lombok features annotation and during compilation it adds some code. So here what I am trying to do is that I am just using well I am not using whether it's
02:30 - 03:00 an string, whether it's an int or what. So it determine from the value. Okay, we will see that later. So here I am using one of the longbox feature but my IntelliJ but your IDE doesn't know that how to treat this well. So that's why it is show compilation error. But when you run it during compilation since we are using we have added the Lombok dependency it. So if you see this
03:00 - 03:30 dotclass file it properly change well to string right it determine from the value but our ID doesn't know that. So for that what we have to do is we have to end the add the Lombok plug-in to our ID. So if you open your IDE settings click on the plugins you have to download this Lombok plug-in.
03:30 - 04:00 And second thing is that in your build IDE settings build execution deployment there is something called annotation processing you have to enable it. So these two things you have to enable it so that your ID also kind of behave what Lombok is going to do during the compile time. Now here if you see that after doing that my ID is not showing any error. Okay because now it is able to
04:00 - 04:30 see what Lombok is going to do during compilation time. How this is going to treat this? Well, my ID is now also aware of that because of this two. Okay, so you have to add the pom.xml plus not mandatory but uh would be helpful for you during coding if you add this plug-in your ID and enable the annotation processing. So with that being said, we
04:30 - 05:00 are good to understand all the Lombok features. So there are so many features. So I will cover 10 frequently used Lombok features right. If you know more there uh is a proper like list of features available. You can go through all right over the internet but I will cover the top 10 features used in the industry. The first one is well and where. So instead of actually writing
05:00 - 05:30 the type we can use this as the type of local variable declaration I have marked it at bold local variable only. Okay we will see that type will be informed from the initializer expression. So what is the type? So currently let's say we are using well some variable name and whatever the expression we will use initialization expression from that it will determine what should be the type of this one. Okay, so that's what this
05:30 - 06:00 line means. And this this one local variable. So it can be used only for local variables, not for fields, not for parameters. Right? Only local variables which is inside a block. Okay, that's what I mentioned in the note. Only works for local variable, not for fields or parameter. So what is the use of well? Marks local variable immutable means it
06:00 - 06:30 will make them final and where is just similar but it do not mark it as final that is the only difference. So take this one example so I have created method okay in that I have created well a equals to 10. Now I am trying to change the value of this a. It says that cannot assign a value to final variable. Why? Because
06:30 - 07:00 well makes local variable immutable. Okay. Similarly, you can use where but it not make it final. So you would be able to change its value also. Okay. And here if you see we don't have to worry about like shall I give it int string object whatever it will determine from this initialization expression. Okay. So that was the first feature. Second feature was at the rate
07:00 - 07:30 not nonnull. So it generate a null check statement and throws null pointer exception if value is null. can be used on a parameter of a method or constructor. See this example. So here I am creating one method and on the parameter I am putting at the rate nonnull. Okay. And I have just put system.out.printerland. This is my java. Now when I compile this my how my
07:30 - 08:00 dotclass looks like. So here if you see that my dot class it added this code for me. if name because on this parameter I put non null line so it put a null check if name equals to equals to null it throws a null pointer exception with a message and then else it will put a system.out.print print ln. So even though my code look like this after compilation the longbox add new code
08:00 - 08:30 right so that's what add the red non null is used it is it can be used on a parameter of a method or constructor only the third feature is getter and setters. So if you see this right we always have most of our POJO classes we need to write getters and setters of the fields. So there are a better way that we can annotate any field with getter and setter annotation and let generate
08:30 - 09:00 the default getter and setter method for us. So this is very very highly used in the industry. You will see this a lot. So here if you see I have created one pojo class and these are the fields and on top of them I have put the annotation getter at the red setter and here's the same at the red getter at the red setter. Now if you see the dotclass file of this the long automatically generate for
09:00 - 09:30 name it will generate the get name and the set name and for committee it will generate the is committee and the set generally this is a get and this is generally a set right. So by default generates getter and setter methods are public. So here if you see all the getter and setter methods which Lombok generates are public okay but we can also control it
09:30 - 10:00 how like this so let's say the getter method for name I want a getter method yes but what is the access level I want private and the setter method what is the uh access level I want protected like this you can make sure that what whether you want to have a private method or protected method or public method. Right? So now here if you see the getter for the name is private. The
10:00 - 10:30 setter for the name is protected. For the committee member I haven't selected the access level. So by default is public. Okay. We can also use this annotation at class level two. So instead of using at each field we can use at the class level itself. So here if you see this is a class I can use at the class level itself. So getter annotation will be applied to all non-static fields. Right?
10:30 - 11:00 So here in this case I have three fields one is a static. So getter field doesn't apply on the static field itself. Okay. And the setter method annotation is applied to all non-static and nonfinal fields. Okay. So for static method also there would be no setter method and for final for final field also there is no setter method. It
11:00 - 11:30 makes sense right? For final fields means you can't change its value. So you don't need its setter method. So that's what it say for setter method even non-static uh setter method annotation is applied to all non-static and non-final fields only. So here if you see is dot class file you will see I have used or at the class level. So for name I will get get name set name for committee members I will get it's kind of a is committee
11:30 - 12:00 member which is a get and it's set and this is a static. So for static there is no getter and also for no setter. Okay. And if there is final let's say some variable int some final you will only get its getter no setter right because setter method is not applicable for final fields only getter you will get get method will get
12:00 - 12:30 generated while using annotation at class level. If you want to skip the default generation of any field, we can do that by using access level.none. So generally what happen is when you use this annotation at class level it it's like this applied to all the fields but you can also control very granular level that say that I have used at class level. So means at this point of time what it
12:30 - 13:00 knows that I have to generate the getter and setter for all the fields but I can control let's say for this field name I don't want setter method so I can put at the rate setter access level none I override eject so for the name you will got the get but there is no setter but for committee you get both get and set Okay. So you can use this to make sure uh that this either setter or
13:00 - 13:30 getter method is not generated. Okay. The fourth feature is add the rate two string. So it is used to generate the two string method. So you might have used in your production code this method which is mostly used for logging right debugging. Many times we need to print what's there in the object and it is generally mostly specifically used for logging and
13:30 - 14:00 debugging purpose. Right? But you will see that this method in your code. So now we can use this annotation long feature to generate this method for us. We don't have to write by ourself. So if let's say that on this class it has this two fields. Now if I use the annotation at the rate two string so this is the dot class file. What it see that it generates a two-string method
14:00 - 14:30 for mean and what it returns the class name right after that bracket the field name the value comma separated another field name and its value bracket close. So this is the default way of returning the value of this method. Okay. But now let's say that hey I have
14:30 - 15:00 multiple fields for some fields I don't want to insert or print into the logs. Right. So we can exclude specific fields also. So now let's say add the red two string but committee member you don't want to print into the logs. So you can do add the two string dot exclude. So that will not come. Okay. Similarly, if you want to skip the field name like here it is
15:00 - 15:30 printing the field name right this is the field name this is the field name you don't want because you know that the size of the logs increase right unnecessary so if you don't want the field name then what you can do is like add the rate to string include field names equals to false so now here if you see that only value is getting printed no field name. Okay, there is another call explicitly selecting the fields. So now
15:30 - 16:00 let's say that I have put at the rate two string on the class. But I have also made that only explicitly included equals to true means only those fields on which I have put this at the rate to string.incclude those only will get added or used. Okay. So even though I have used at the rate to string at the class level, I have made that only explicitly included.
16:00 - 16:30 If it is true, then only it would get should be used. So we have to use this add the two string dotincclude. Okay. Then next feature we have is that no r constructor required ask constructor all our constructor. From the name it's very clear. No ask constructor mean generate no argument constructor. All asks constructor means generate constructor with all the fields. Required ask constructor
16:30 - 17:00 generate constructor with only final and not null fields. Now at this point of time you can suddenly one question comes to your mind. How come in the previously non-null we mentioned that it is used only at the parameter and constructor. right? Not on the fields. So I will show you how it's used on the fields. How it is used? It is mostly used on constructor only. Okay? But how? I'll tell you. So see this example. So on
17:00 - 17:30 this class I have used all this annotation. No r constructor all our constructor required ar constructor. So here if you see I have one name boolean committee member and one non-null value. So here it say that first it generated a no r constructor this one then it generated a all r constructor so all are mean all three values name committee member and age now
17:30 - 18:00 since age I have put non-null right so here if you see generally now it used as a parameter of a constructor right so here it put a null check if age equals to equals to null throw null pointer exception right otherwise assign the value initialize the value right and the third is required ask constructor so here if you see required ask constructor is only used
18:00 - 18:30 for final and non-null fields so only for this non-null age this constructor is created with only age and since age is non-null so it put a null check first and then initializes Right. Then next feature which Lombok provide is equals and hashcode annotation. I have already explained
18:30 - 19:00 this equals and hash code method in this Java hashmap internal working right. What is the contract between equals and hash code and how internally it works. So generally we can use Lombok to create the equals method and hash code method for us. Okay. So by default it uses all non static and non-transient fields. So see this example on this class I have put this
19:00 - 19:30 annotation at the rate equals and hash code. Okay. And I have also make sure that this committee member I don't want to include it into the equals and hash code method. I want to exclude it. Right? So we can do that. The same thing I showed you previously. Right? We can include we can exclude individual values also. So I want to exclude it. So I added this. Now if you see the dot clause file
19:30 - 20:00 generated it created my equals method for me with only this field right statics are skipped and even this one which I excluded it that is also skipped and it is also created a hashcode method for me okay and the code which it generates follow the contract which equals and hash code method follows. So we don't have to worry about that. Okay. Then there is another
20:00 - 20:30 feature is called data. So data is like you can say that again a shortcut for all this one. So it's like plus+ plus data is equivalent of two string equal and hash code getter on all fields setter on all non-final fields and it's a required ar constructor. So here if you see this is my code I have one field name string one final and
20:30 - 21:00 one at the rate non-null and I have just put at the rate data and when I compile it see the amount of code it generated for me right so what it does it created one two-string method for me so here if you see the two string method is created the hash code and equals method is created. Okay. Now here if you see the getter on all fields so means name, age,
21:00 - 21:30 address. So get name, get age, get address. Okay. The setter on nonfinal fields, right? So you will find a setter for name. So here you will see setter for name and setter for address. And since address is non-null, it put a null check first and then initializes it. But there is no
21:30 - 22:00 setter method for the age. Okay. And then required asks constructor. So required ask constructor means constructor for either non-null and final. So one constructor for non-null one address and the final variable right. So you can say that at the rate data is just a shortcut for all of this right and see the lot of code it has generated for us just our code is
22:00 - 22:30 just this. Similarly we have add the value you can say that it's an immutable version of data. So what it does is it made all fields private and final first immutable version. So it make it all fields private and final. It made class itself made final. It can't be subclassed. Right? The setters are not generated. Why? Because since all fields
22:30 - 23:00 are made final for final no setter class. So no setter methods are generated. two strings and equal and hash code method generated like data getter on all fields will be generated. Now add the rate required as constructor would be applied. But since all fields are final means all fields would be present into the constructor which is equivalent to now all ask constructor. You know right required ask constructor only have two kind of uh
23:00 - 23:30 take care of final and final and nonnull. Now since this value makes all fields private and final. So means all the fields would be there in the constructor and since all the fields are there in the constructor it is equivalent to all arts constructor. So here this is my code and I have put at the rate value. Now here if you see this is the dotclass file it generated lot of code two string
23:30 - 24:00 equals and hashcode method generated right and the getter method for all. It generated the getter method for all. And also here if you see it created a constructor since it made all final private final right. So all final one would be there name age address which is now equivalent to all last
24:00 - 24:30 constructor. Okay. One another feature is builder annotation. So in the L&D playlist I have told about the builder pattern right? So builder pattern is used for two things. One is that we can create object parts by parts. Second helps to create object immutable. Okay. So I have already explained how builder design pattern
24:30 - 25:00 works. So here in Java let's say for this class you have to have a builder pattern. All you have to do is this use this annotation add the red builder. If you see dot class file it create one builder class for you. It creates one builder class for you. And here if you see it has like you can set the name you can set the age and you can create it in parts by part. The return value is still
25:00 - 25:30 builder right and later on when you do build then only it creates a ultimate object. So that's what we do in the builder pattern. So now all this code is generated by this annotation itself. So now here all we can do is like test pojo dot builder right. So here is the dot builder. It will create a builder object this class which is newly created. Now we can set part by part. We can set
25:30 - 26:00 age. We can set name. Okay. So age is still return the builder object. Name is still return the builder object. And later on when all created when do called build ultimately return the test pojo object. And now once you get the object can you change it? There is no setter value. Okay. So here if you see in the test pojo there is no setter methods. So that's why generally say that builder pattern also helps to achieve
26:00 - 26:30 immutability. We can easily achieve that. So we if you want to know more about in depth of the builder pattern you can check this video otherwise uh if it is already clear then we can directly use this annotation and our work is done. And the last feature which is highly used is the cleanup. It ensures that the given resource is automatically cleaned up before execution path exit the current scope. So here if you see
26:30 - 27:00 this is my Java class I am using an file input stream want to read some data from the file I am reading it right and here if you see I haven't closed it all I used it on this input stream I just put add the rate cleanup now if you see the dotclass file it put try cache finally block for me and in the finally block it is closing it so this is taking care of it. So any
27:00 - 27:30 resource which you want to make sure that after the current scope it should get closed we can use at the rate cleanup annotation. So these are top 10 features of the longbox. There are many which you can go through but if you are going through your live production ready code this 10 you will see very very frequently used and if you have doubt with any of this
27:30 - 28:00 feature let me know we can discuss further into the comment section. Okay guys, thank you. Bye.