Java Lombok | Automatically Calling close() - @Cleanup

Using @Cleanup

If you declare the @Cleanup annotation on a local variable, the close() method is called when execution leaves the scope.

package com.devkuma.tutorial.lombok;

import lombok.Cleanup;

public class CleanupTutorial {
    public static void main(String[] args) {
        @Cleanup CleanupTutorial cleanupTutorial = new CleanupTutorial();
    }

    public void close() {
        System.out.println("close 메소드가 호출되었습니다.");
    }

    public void close(String arg) {
        System.out.println("close(String) 메소드가 호출되었습니다.");
    }
}

Execution result:

close 메소드가 호출되었습니다.

Specifying a Method for @Cleanup

You can also specify the method to execute as follows.

package com.devkuma.tutorial.lombok;

import lombok.Cleanup;

public class CleanupTutorial2 {
    public static void main(String[] args) {
        @Cleanup("dispose") CleanupTutorial2 cleanupTutorial = new CleanupTutorial2();
    }

    public void close() {
        System.out.println("close 메소드가 호출되었습니다.");
    }

    public void dispose() {
        System.out.println("dispose 메소드가 호출되었습니다.");
    }
}

Execution result:

dispose 메소드가 호출되었습니다.
  • By specifying dispose as the value, the dispose() method was executed.