Skip to content

[java] CloseResource false-positive on Pattern Matching with instanceof #5042

@Wolf2323

Description

@Wolf2323

Affects PMD Version: 7.1.0

Rule: CloseResource

Please provide the rule name and a link to the rule documentation:
https://pmd.github.io/pmd/pmd_rules_java_errorprone.html#closeresource

Description:
Since PMD 7 the Pattern Matching with instanceof detects closable resources as false positive in my opinion. Maybe my code is not that perfect, and I should simply suppress it.

Code Sample demonstrating the issue:

    private void loadFromObject(@Nullable final Object input, final YamlConfiguration config) throws IOException, InvalidConfigurationException {
        if (input instanceof final File file) {
            config.load(file);
        } else if (input instanceof final Reader reader) { // <-- Violation
            config.load(reader);
        } else if (input instanceof final String string) {
            config.load(string);
        }
    }

While i have already this code two methods layers above

            try (InputStreamReader reader = new InputStreamReader(str, StandardCharsets.UTF_8)) {
                return load(reader, true, resourceFile);
            }

Expected outcome:
no violation, as the resource is not opened in the instanceOf check (and already autoclosed above)

[INFO] PMD Failure: org.betonquest.betonquest.modules.config.ConfigAccessorImpl:113 Rule:CloseResource Priority:3 Ensure that resources like this Reader object are closed after use.

Running PMD through: Maven

Metadata

Metadata

Assignees

No one assigned

    Labels

    a:false-positivePMD flags a piece of code that is not problematic

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions