-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
[java] NullAssignment: False positive when assigning null to a final field in a constructor #6276
Copy link
Copy link
Closed
Labels
a:false-positivePMD flags a piece of code that is not problematicPMD flags a piece of code that is not problematic
Milestone
Description
Affects PMD Version: 7.18.0
Rule: NullAssignment
Description:
If you have a final field that might be null or not, depending on the called constructor or depending on the arguments given to the constructor, you must set it to null explicitly in the constructor.
If you set it at declaration time, you cannot set it to a different value.
So assigning null to a final field in a constructor should not trigger a finding.
This does sometimes work as expected for example when directly assigning null, but if it is done as part of a ternary expression for example, the rule complains.
Code Sample demonstrating the issue:
import java.time.Instant;
public class Version {
private final Instant buildTimestamp;
public Version(String buildTimestamp) {
this.buildTimestamp = "$buildTimestamp".equals(buildTimestamp) ? null : Instant.parse(buildTimestamp);
}
}Expected outcome:
PMD reports a violation at line 95, but that's wrong. That's a false positive.
Running PMD through: Gradle
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
a:false-positivePMD flags a piece of code that is not problematicPMD flags a piece of code that is not problematic