Java - Lombok @Cleanup Use Case

Subscribe Send me a message home page tags



In this post, we try to use the @Cleanup feature of Lombok to replicate the with block in Python. The most significant feature of the with block in python is that the magic method __exit__ is guaranteed to be executed no matter what happens during the execution of the block. This is exactly what @Cleanup annotation achieves in the Lombok. Note that all these features can be achieved with normal try-catch block.

We first define a CodeBlock. It will have three methods: (1)enter (2)exit and (3) run. The @Cleanup will work behind the sceen when a local variable is out of scope. In order to triger the event, we create a local reference of the CodeBlock in a method called with. The enter and run method of the CodeBlock object will be called in order. The exit part is taken care by the @Cleanup automatically.

The only thing left is to implement the run methods of the CodeBlock class. The code we write in this method is the counterpart of the code in a python with block.

The code below show the use case of our simple replicate of the python with block in java.
package PracticeLombok;

import lombok.Cleanup;

public class CleanupLab {

    public interface CodeBlock {
        default void enter() {};
        default void exit() {};
        default void run() {};
    }


    public static void with(final CodeBlock codeBlock) {
        @Cleanup("exit") CodeBlock cb = codeBlock;
        cb.enter();
        cb.run();
    }

    private static class SampleCodeBlock implements CodeBlock {
        public void enter() {
            System.out.println("Entering SampleCodeBlock");
        }

        public void exit() {
            System.out.println("Exiting SampleCodeBlock");
        }

    }

    public static void main(String[] args) {

        with(new SampleCodeBlock() {
            public void run() {
                System.out.println("Example 1:");
                System.out.println("Running the code inside the block.");
            }
        });

       System.out.println("\n------\n"); 

        with(new SampleCodeBlock() {
            public void run() {
                System.out.println("Example 2:");
                System.out.println("Running the code inside the block");
                System.out.println("We throw an exception and the exit block will still be executed");
            }
        });
    }
};

Here is the output.
Entering SampleCodeBlock
Example 1:
Running the code inside the block.
Exiting SampleCodeBlock

------

Entering SampleCodeBlock
Example 2:
Running the code inside the block
We throw an exception and the exit block will still be executed
Exiting SampleCodeBlock

----- END -----

Welcome to join reddit self-learning community.
Send me a message Subscribe to blog updates

Want some fun stuff?

/static/shopping_demo.png