#21751·checkstyle

RequireThis: false negative for a field shadowed by a resource in finally

Author: ishu7wCreated Sep 27, 2026Updated Sep 27, 2026
Labelsapproved

I have read check documentation: https://checkstyle.org/checks/coding/requirethis.html I have downloaded the latest Checkstyle from: https://checkstyle.org/cmdline.html#Download_and_Run I have executed the CLI as shown below.

Reproduction

Checkstyle 14.3.0, macOS, Java 21. The example compiles successfully.

java
class Example {
    private Object resource;

    void run() throws Exception {
        try (AutoCloseable resource = () -> { }) {
            System.out.println(resource);
        } finally {
            System.out.println(resource);
        }
    }
}
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="RequireThis">
      <property name="validateOnlyOverlapping" value="false"/>
      <property name="checkMethods" value="false"/>
    </module>
  </module>
</module>
$ javac Example.java
$ java -jar checkstyle-14.3.0-all.jar -c config.xml Example.java
Starting audit...
Audit done.

The same missing violation occurs on master 80ebbfff48f257a775b516fda1f6bb3976bcc80f.

Expected behavior

Report a violation at line 8, column 32:

Reference to instance variable 'resource' needs "this.". [RequireThis]

The reference in the try body is the local resource and should not be reported. The reference in the associated finally block resolves to the instance field, because the resource declaration is no longer in scope. Explicit this.resource in finally should remain valid.

JLS 6.3 limits a resource variable's scope to the resource specification from its declaration onward and the associated try block; it does not include the catch or finally clauses.

Investigation and proposed fix

RequireThisCheck already skips the try-with-resources declaration frame for catch-block lookup, but the finally block's frame still points to the resource frame. This incorrectly resolves the field reference as a resource and suppresses the violation.

A local fix creates the finally block's frame with the parent of its associated resource frame, preserving any enclosing resources and other local scopes. The patched CLI reports the expected violation. A new repository regression test fails on unmodified master with seven missing violations across finally, multiple-resource, and nested-resource cases. Full validation is in progress.

Related: #6845 concerns resource visibility inside the try body; this report concerns resource declarations leaking into finally. I found no existing report specifically covering this case.

I am working on the fix and regression tests and will submit a PR after issue approval. Codex assisted with the investigation, implementation, and validation.