projectlombok / lombok

Very spicy additions to the Java programming language.
https://projectlombok.org/
Other
12.9k stars 2.39k forks source link

[FEATURE] Why annotation `@Cleanup` use a singletonList to judge null #3258

Open samho2008 opened 2 years ago

samho2008 commented 2 years ago

Java Code:

    public static void main(String[] args) throws IOException {
        @Cleanup Reader fileReader = new FileReader("hello.txt");
    }

Decompiled Class Code:

    public static void main(String[] args) throws IOException {
        Reader fileReader = new FileReader("hello.txt");
        if (Collections.singletonList(fileReader).get(0) != null) {
            fileReader.close();
        }

    }

The question is why use a singletonList to judge null, instead of fileReader != null?

Rawi01 commented 2 years ago

Historical reasons I guess, the message of the commit that added theses lines:

Rewritten @Cleanup's new null analysis prevention to not use
Lombok.preventNullAnalysis but go with Collections.singletonList(expr).get(0)
instead; while this does create a pointless object, it doesn't cause a clash
when eclipse has lombok 0.10 installed but the project uses 0.9, which doesn't
have preventNullAnalysis. Eventually, once 0.9 is long forgotten, this can be reverted.
magicprinc commented 11 months ago

I think @Cleanup is a great feature and must not be abandoned, but improved!

The bad thing is: if a "close" method throws an exception, it completely replaces the original exception from the body. Better: Swallow the exception from close Event better Java 7 Suppressed exceptions