pmd / pmd

An extensible multilanguage static code analyzer.

Home Page:https://pmd.github.io

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

BigIntegerInstantiation false positive with new BigDecimal( 2 )

esfomeado opened this issue · comments

Affects PMD Version:
7.1.0

Rule:

Please provide the rule name and a link to the rule documentation:
https://docs.pmd-code.org/pmd-doc-7.1.0/pmd_rules_java_performance.html#bigintegerinstantiation

Description:

Code Sample demonstrating the issue:

public interface EvaluationValue 
{
    static EvaluationValue of( BigDecimal value )
    {
        return new NumberEvaluationValue( value );
    }
}

public record NumberEvaluationValue( BigDecimal value )
    implements EvaluationValue
{
    public NumberEvaluationValue( BigDecimal value )
    {
        this.value = value ;
    }
}

...
EvaluationValue.of( new BigDecimal( 2 ) );
...

Expected outcome:

PMD reports a violation on the new BigDecimal( 2 ) because it thinks it can be replaced with BigInteger.TWO which is not possible.

Running PMD through: Gradle

@esfomeado BigDecimal.TWO exists and is valid starting from Java 19. The rule is aware of that and reports it accordingly when the Java version in use allows for it.

So, I'm a little confused as to why you say "it thinks it can be replaced with BigInteger.TWO which is not possible.".

Your project is either using Java 19+ and the replacement should be possible, or your Gradle project is misconfigured, and is running PMD for a Java version that doesn't match your actual program.

PMD 7.1.0's default language version is Java 22 so that's probably what happens to be picked up, which explains the violation. However I looked quickly through the gradle docs and it is not obvious at all how to configure the language version. It has a property for targetJdk which only goes as far as 1.7, and reportedly is there only for PMD < 5.0 (source).

Yes, it seems Gradle is never actually configuring the language version when running PMD, so it always defaults to latest.

Fixing this lies on Gradle however. I've found this issue gradle/gradle#21519 where the lack of proper language version configuration (and therefore preview features) are mentioned.

There was even this (now abandonded) PR that added support for it: gradle/gradle#21590

I will close this as it's indeed an issue with Gradle.