org.openrewrite.staticanalysis.NoFinalizedLocalVariables Maven / Gradle / Ivy
Show all versions of rewrite-static-analysis Show documentation
/*
* Copyright 2024 the original author or authors.
*
* Licensed under the Moderne Source Available License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://docs.moderne.io/licensing/moderne-source-available-license
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openrewrite.staticanalysis;
import org.openrewrite.*;
import org.openrewrite.internal.ListUtils;
import org.openrewrite.java.JavaIsoVisitor;
import org.openrewrite.java.tree.J;
import java.util.Iterator;
@Incubating(since = "7.0.0")
public class NoFinalizedLocalVariables extends Recipe {
@Override
public String getDisplayName() {
return "Don't use final on local variables";
}
@Override
public String getDescription() {
return "Remove the `final` modifier keyword from local variables regardless of whether they are used within a local class or an anonymous class.";
}
@Override
public TreeVisitor, ExecutionContext> getVisitor() {
return new JavaIsoVisitor() {
@Override
public J.VariableDeclarations visitVariableDeclarations(J.VariableDeclarations multiVariable, ExecutionContext ctx) {
J.VariableDeclarations mv = super.visitVariableDeclarations(multiVariable, ctx);
// if this doesn't have "final", we don't need to bother going any further; we're done
if (!mv.hasModifier(J.Modifier.Type.Final)) {
return mv;
}
Tree parent = getCursor().getParentTreeCursor().getValue();
if (parent instanceof J.MethodDeclaration || parent instanceof J.Lambda) {
// this variable is a method parameter or lambda parameter
return removeFinal(mv);
}
Iterator