rewrite
rewrite copied to clipboard
InstanceOfPatternMatch removes try-with-resource variable
Given the code
if (object instanceof JarArtifact) {
try (JarArtifact a = (JarArtifact) object) {
a rewrite using InstanceOfPatternMatch
results in
if (object instanceof JarArtifact a) {
try () {
A fix could be to simply remove the parenthesis
if (object instanceof JarArtifact a) {
try {
but that may leave the object unclosed, so it should probably be left alone.
Thanks for the report! That would be a bug indeed; we should not make that change when the assignment is in a try-with-resources-try-block. Is this something you'd want to help fix? Even a draft PR with just a unit test added would already help.
I forget in which Java version this was, but possibly 9, the syntax allows for an expression in try-with-resources and doesn't mandate declaring a new variable. So with an appropriate language version we can leverage that.
Yes 9 https://bugs.openjdk.org/browse/JDK-7196163
@timtebeek I'll have a go at it. How to detect Java source version?
Awesome, thanks for the offer to help! We determine the Java version when we parse the project, and store that in a marker called JavaVersion
. A common pattern is to define a Precondition through UsesJavaVersion, to limit when a recipe should apply.
https://github.com/openrewrite/rewrite/blob/03c458404073082275a752063887c188d213afbe/rewrite-java/src/main/java/org/openrewrite/java/search/UsesJavaVersion.java#L30
In rare cases we one can also read the marker directly, but use that only when preconditions aren't an option.
In this particular case we probably don't need anything in addition, as instanceof pattern variables were added in Java 11. So that precondition is already a given.