Skip to content

Add CleanupTryWithResources - #1046

Open
sullis wants to merge 1 commit into
openrewrite:mainfrom
sullis:cleanup-try-with-resources
Open

Add CleanupTryWithResources#1046
sullis wants to merge 1 commit into
openrewrite:mainfrom
sullis:cleanup-try-with-resources

Conversation

@sullis

@sullis sullis commented Sep 1, 2026

Copy link
Copy Markdown

Adds a CleanupTryWithResources recipe that removes the redundant final modifier from resources declared in a try-with-resources statement. Such resources are implicitly final (JLS 14.20.3), so the modifier adds no meaning.

// before
try (final BufferedReader reader = new BufferedReader(in)) {
}

// after
try (BufferedReader reader = new BufferedReader(in)) {
}

Notes on the implementation:

  • Java-only, gated behind JavaFileChecker.
  • Formatting is preserved carefully: comments living in the removed modifier's prefix are carried onto the following token, and a declaration that was wrapped around final is collapsed back onto one line. Initializers keep their own layout, so a multi-line new ...(...) is not reflowed.
  • A final modifier that carries its own annotations is left alone, since dropping it would lose them.
  • Leading annotations on the declaration keep their own prefix whitespace.
  • The recipe is registered in META-INF/rewrite/recipes.csv; it is intentionally not added to common-static-analysis.yml.

Test coverage (CleanupTryWithResourcesTest, 12 cases):

  • single resource, explicit type, and multi-line declarations
  • multiple resources, including when only one of them is final
  • leading annotations retained alongside the removed modifier
  • comments between final and the type, between an annotation and final, and a line comment with its line break
  • no-op cases: a resource without final, and a resource referencing an existing variable

🤖 Generated with Claude Code

@github-project-automation github-project-automation Bot moved this to In Progress in OpenRewrite Sep 1, 2026
@sullis
sullis marked this pull request as ready for review September 1, 2026 19:46
@sullis
sullis force-pushed the cleanup-try-with-resources branch from 786932a to 3dba993 Compare September 1, 2026 19:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: In Progress

Development

Successfully merging this pull request may close these issues.

1 participant