Ah, Project Lombok is one of those little gems in the Java Ecosystem. But it’s interestingly controversial! Some will love it (as I do), others will hate it! But no matter which camp you land on, you should at least know about it!
Project Lombok allows you to, quite easily create your equals/hashcode method, or create a builder pattern for your class, or even generate your getters/setters. All while just adding a simple annotation to your class. How does it do it? (hint. It’s preprocessing bytecode magic) But holy cow, when used responsibly, Lombok allows you to write so little code for a ton of cases. So come take a look at why this library is powerful (and learn its benefits, and as importantly, its pitfalls)
FOLLOW US JavaPubHouse on twitter! Where we will be sharing new tech news, and tutorials!
We also have been revamping our site so go there, take a look, listen to old episodes, or search them!
We thank DataDogHQ for sponsoring this podcast episode
Don’t forget to SUBSCRIBE to our cool NewsCast! Java Off Heap
Do you like the episodes? Want more? Help us out! Buy us a beer!
And Follow us! @javapubhouse and @fguime and @bobpaulin
3 comments on Episode 81. Let’s Dive into a cool magical library that makes Java way less verbose!
Thanks for this episode!
FYI, Lombok does not do any bytecode manipulation. It implements Java Annotation Processor API (javax.annotation.processing.Processor) and modifies the source code (AST tree) between parsing and compiling phases. Whatever you can see using the “delombok” feature is the actual code, which compiler sees.
Another thing I’d like to mention is that you might have problems with your code coverage. I use Jacoco, and here is the solution. You need to put a file “lombok.config” with one line “lombok.addLombokGeneratedAnnotation = true”. Having this, Lombok will put additional run-time annotations above all generated methods and Jacoco later will exclude these methods from the coverage report.
Lombok has been production-ready for a long time. It’s used by many major projects, including Spring.
Oh shucks! Wow, that would explain why enabling annotation preprocessing is all that’s needed!
And that tip for code coverage is great! Thanks Vitaly!
Will make sure to mention it in our next episode
@Data has another benefit when modifying class by removing or adding fields. Without annotation, there is additional work of making constructor, getter, setter, equals, hashcode and tostring changes.
One pitfall of @Data I noticed (and got caught by) is with JPA entities with relations to other entities. By default, generated toString, equals and hashCode use all fields of a class. It compiles, but a call to toString or equals/hashCode will land us a StackOverflowException. Adding explicit @ToString and @EqualsAndHashcode with field listings is a must in case of entities. By the way, there is a nice feature in these two annotations. We can list fields that are to be used or specify it other way, what fields to exclude.