Affects PMD Version:
PMD 7.24.0
Rule:
UseStandardCharsets
Description:
The UseStandardCharsets rule reports calls to Charset.forName(...) when the charset can be replaced by a constant from StandardCharsets, for example StandardCharsets.UTF_8.
However, the rule currently only matches exact uppercase string literals such as "UTF-8". It does not report semantically equivalent lowercase or mixed-case standard charset names, such as "utf-8" or "Utf-8".
According to the Java Charset specification, charset names are not case-sensitive. Therefore, Charset.forName("utf-8") resolves to the same standard UTF-8 charset as Charset.forName("UTF-8"). Since PMD already reports Charset.forName("UTF-8"), it should also report Charset.forName("utf-8").
Current behavior:
Charset.forName("utf-8") -> no violation, exit code 0
Charset.forName("UTF-8") -> violation reported, exit code 4
For the uppercase variant, PMD reports:
/tmp/ReproUseStandardCharsetsUpper.java:5: UseStandardCharsets: Please use StandardCharsets constants
This suggests that the rule is active and works for exact uppercase literals, but misses lowercase standard charset names. This is a false-negative.
Code Sample demonstrating the issue:
import java.nio.charset.Charset;
class ReproUseStandardCharsets {
Charset charset() {
return Charset.forName("utf-8"); // <-should report(FN)
}
}
Expected outcome:
PMD should report a violation at line 5, but doesn't. This is a false-negative.
Expected replacement:
return StandardCharsets.UTF_8;
Running PMD through: CLI
Example command:
pmd check -d ReproUseStandardCharsets.java \
-R category/java/bestpractices.xml/UseStandardCharsets \
-f text --no-progress
Affects PMD Version:
PMD 7.24.0
Rule:
UseStandardCharsets
Description:
The
UseStandardCharsetsrule reports calls toCharset.forName(...)when the charset can be replaced by a constant fromStandardCharsets, for exampleStandardCharsets.UTF_8.However, the rule currently only matches exact uppercase string literals such as
"UTF-8". It does not report semantically equivalent lowercase or mixed-case standard charset names, such as"utf-8"or"Utf-8".According to the Java
Charsetspecification, charset names are not case-sensitive. Therefore,Charset.forName("utf-8")resolves to the same standard UTF-8 charset asCharset.forName("UTF-8"). Since PMD already reportsCharset.forName("UTF-8"), it should also reportCharset.forName("utf-8").Current behavior:
For the uppercase variant, PMD reports:
This suggests that the rule is active and works for exact uppercase literals, but misses lowercase standard charset names. This is a false-negative.
Code Sample demonstrating the issue:
Expected outcome:
PMD should report a violation at line 5, but doesn't. This is a false-negative.
Expected replacement:
Running PMD through: CLI
Example command: