Cleanup resource automatically with Project Lombok

When we use a resource like InputStream, OutputStream in Java, we should remember to close that resource after using.

Before Java 7, we can close a resource in a finally block as below:

Since Java 7, we can use the try with resource to close the resource automatically as below:

Using try with resource, Java will invoke the method close() of the resource after using automatically.

With Project Lombok, we have another alternative way to close a resource automatically by using @Cleanup annotation:

In this case, if you check the file Example.class in /target/classes/com/huongdanjava/lombok, you will see the content as below:

Using @Cleanup annotation, we can also declare the method name of close method in the case the close method of resource is not named close(). Like below:

Đánh giá bài viết
Chia sẽ bài viết này ...Share on Facebook
Facebook
0Tweet about this on Twitter
Twitter
Share on LinkedIn
Linkedin

Add Comment

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