toString(), equals() and hashCode() method with Project Lombok

In many situations working with Java object, we need define toString(), equals() or hashCode() method. These method can be added into the Java object automatically by using Project Lombok. In this tutorial, I will show you all about this!

First of all, we need a Maven project for example:

toString(), equals() and hashCode() method with Project Lombok

with Project Lombok dependency as below:

Remember that, we need install Project Lombok plugin into our IDE. See construction for IntelliJ IDEA at here.

Now, for example, I have a Student class with some information like name, code, dateOfBirth. Without using Lombok library, I must declare the method toString(), equals() and hashCode() method (other Getter, Setter methods or constructors, I defined with Project Lombok) like below:

We can automate this by using @ToString and @EqualsAndHashCode annotation as below:

  • @ToString: will generate toString() method with all class fields. We no need to maintain this method when we add more and remove some fields.
  • @EqualsAndHashCode: this annotation will help Project Lombok generate the method equals() and hashCode() with all class nonstatic and nontransient fields automatically.

Now, if you check in the folder /target/classes/com/huongdanjava/lombok, the content of Student.class will be as below:

You can see, because the field code in Student bean was declared as transient field, then in generated equals() and hashCode() method, we didn’t see it included.

Now, if we have 2 Student objects with difference code, same name and dateOfBirth, when comparing, you will still see them same. For example:

Result:

toString(), equals() and hashCode() method with Project Lombok



You can exclude some fields which we don’t want to include in toString(), equals() and hashCode() method by declaring exclude attribute in @ToString and @EqualsAndHashCode annotation.

For example, now, I want to exclude dateOfBirth field in Student bean, I will declare as below:

Now, if you check in the folder /target/classes/com/huongdanjava/lombok, the content of Student.class will be as below:



toString(), equals() and hashCode() method with Project Lombok
5 (100%) 1 vote
Chia sẽ bài viết này ...Share on Facebook
Facebook
2Share on Google+
Google+
0Tweet about this on Twitter
Twitter
Share on LinkedIn
Linkedin

One thought on “toString(), equals() and hashCode() method with Project Lombok

Add Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.