-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
[java] CloseResource false-positive on Pattern Matching with instanceof #5042
Description
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