@Cleanup calling custom method

In the previous post under Lombok, I explained with purpose of “@Cleanup” annotation.

“@Cleanup” annotation applied to any field assumes it as a resource and closes it just before the program ends.

By default it assumes that the annotated field or resource or the instance has a method named “close” and when the time comes to close the resource Lombok framework calls the “close” method.

Now we change this assumption. In other words we can configure Lombok framework to call a method named other than “close” on the resource to close it.

We do this by setting the annotations “value” attribute as shown in the below example.

For our example I will create a mock resource named “MockResource”.

MockResource

package package25;

public class MockResource {
public MockResource() {
System.out.println("constructor method");
}

public void performAction() {
System.out.println("action performed");
}

public void destroy() {
System.out.println("destroy method");
}
}

As shown above I have created a resource class named “MockResource”, it has constructor, a method defining the action to be performed by the resource, and another method “destroy” which will close this mock resource.

Note: In Java, whenever we use “try with resource” block, we have to make sure that the resource or instance implements the “AutoCloseable” interface. We don’t have such restrictions here.

Next I will show the main class where this resource is used and which shows how to change the method name that has to be called when closing the resource annotated with “@Cleanup” annotation.

Main class

1  package package25;
2
3 import lombok.Cleanup;
4
5 public class Example25 {
6 public static void main(String[] args) {
7 @Cleanup("destroy") MockResource mockResource = new MockResource();
8 mockResource.performAction();
9 }
10 }

As you can see in the above code, at line 7, I create an instance of “MockResource” class and at the same time annotate its reference with “@Cleanup” annotation. I also pass the method name “destroy”
available in the “MockResource” as an argument to “@Cleanup” annotation. This informs Lombok to call “destroy” method on “MockResource” instance instead of searching for method named “close” and calling it.

In this way we can change the default behavior of “@Cleanup” annotation.

In this way we can configure the “@Cleanup” annotation to call a custom method.

Below is the output

Output

constructor method
action performed
destroy method

Leave a comment