Skip to content

[java] LambdaCanBeMethodReference: False positive with array creation containing constructor call in receiver #6709

Closed

Description

@mmnhgo

Affects PMD Version: 7.24.0

Rule:

LambdaCanBeMethodReference

Description:
The rule reports a false positive for a lambda whose method-call receiver contains an array creation expression with a nested constructor call.
The official documentation explicitly states that the rule will not report lambdas of the form x -> new CtorCall().something(x) because converting to a method reference would change the object creation timing (one object at method-ref creation time vs. one object per lambda invocation).
This reproducer has exactly the same semantic issue, but the constructor call is hidden inside an array initializer (new Holder[] { new Holder() }[0]). The current implementation in canBeTransformed() only excludes a top-level ASTConstructorCall and therefore incorrectly suggests the transformation.

Code Sample demonstrating the issue:

import java.util.function.IntPredicate;

public class Repro {
    static IntPredicate p() {
        return x -> new Holder[] { new Holder() }[0].test(x); //<-should not report
    }

    static class Holder {
        boolean test(int x) {
            return x > 0;
        }
    }
}

Expected outcome:
PMD should not report any violation.
The suggested method reference new Holder[]{ new Holder() }[0]::test changes the program semantics (array + Holder are created only once instead of on every lambda invocation). This is a false positive.

Running PMD through: CLI

Activity

  1. added
    a:false-positive
    on May 24, 2026
  2. changed the title [-][java] LambdaCanBeMethodReference false positive with array creation containing constructor call in receiver[/-] [+][java] LambdaCanBeMethodReference: False positive with array creation containing constructor call in receiver[/+] on May 25, 2026
  3. added a commit that references this issue on Jul 1, 2026
    075f077
  4. added this to the 7.27.0 milestone on Jul 6, 2026
  5. added a commit that references this issue on Jul 6, 2026
    e1a5bf3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    a:false-positive

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions