#21611·checkstyle

PatternVariableAssignment: false positive when assigning a same-named field inside an anonymous or local class

Author: anushkagupta200615-jpgCreated Sep 16, 2026Updated Sep 17, 2026
Labelsapproved

I have read check documentation: https://checkstyle.org/checks/coding/patternvariableassignment.html I have downloaded the latest checkstyle from: https://checkstyle.org/cmdline.html#Download_and_Run I have executed the cli and showed it below, as cli describes the problem better than 1,000 words

bash
D:\temp\checkstyle-repro>javac Anon.java

D:\temp\checkstyle-repro>type config.xml
<?xml version="1.0"?>
<!DOCTYPE module PUBLIC
  "-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"
  "https://checkstyle.org/dtds/configuration_1_3.dtd">
<module name="Checker">
  <module name="TreeWalker">
    <module name="PatternVariableAssignment"/>
  </module>
</module>

D:\temp\checkstyle-repro>type Anon.java
public class Anon {
    void test(Object o) {
        if (o instanceof String s) {
            Runnable r = new Runnable() {
                private String s;

                @Override
                public void run() {
                    s = "field of anonymous class";
                }
            };
            r.run();
        }
    }

    void local(Object o) {
        if (o instanceof String s) {
            class Local {
                String s;

                void set() {
                    s = "field of local class";
                }
            }
            new Local().set();
        }
    }
}

D:\temp\checkstyle-repro>set RUN_LOCALE="-Duser.language=en -Duser.country=US"
D:\temp\checkstyle-repro>java %RUN_LOCALE% -jar checkstyle-14.1.0-all.jar -c config.xml Anon.java
Starting audit...
[ERROR] D:\temp\checkstyle-repro\Anon.java:9:21: Assignment of pattern variable 's' is not allowed. [PatternVariableAssignment]
[ERROR] D:\temp\checkstyle-repro\Anon.java:22:21: Assignment of pattern variable 's' is not allowed. [PatternVariableAssignment]
Audit done.
Checkstyle ends with 2 errors.

Describe what you expect in detail.

No violations are expected.

Inside the anonymous class (line 5) and the local class (line 19), a field named s is declared. This field shadows the pattern variable s from the enclosing instanceof. The assignments on lines 9 and 22 write to that field of the nested class, not to the pattern variable, so the pattern variable is never reassigned. The code compiles successfully.

The check matches assigned identifiers to pattern variables by name only, without stopping at nested class boundaries (anonymous class body / local class) where a field with the same name shadows the pattern variable.

Related (already fixed) false positive for the this.s = ... case: #18132