io.slugstack.rewritejavarecipes.GenerateSetter Maven / Gradle / Ivy
Show all versions of rewrite-java-recipes Show documentation
package io.slugstack.rewritejavarecipes;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.openrewrite.Cursor;
import org.openrewrite.ExecutionContext;
import org.openrewrite.Recipe;
import org.openrewrite.TreeVisitor;
import org.openrewrite.internal.StringUtils;
import org.openrewrite.java.JavaIsoVisitor;
import org.openrewrite.java.JavaTemplate;
import org.openrewrite.java.tree.J;
import org.openrewrite.java.tree.TypeUtils;
@Data
@EqualsAndHashCode(callSuper = true)
public class GenerateSetter extends Recipe {
private final String fieldName;
@Override
public String getDisplayName() {
return "Generate setter";
}
@Override
public String getDescription() {
return "Generate setter method for a given class field.";
}
@Override
protected TreeVisitor, ExecutionContext> getVisitor() {
return new GenerateSetterVisitor<>();
}
private class GenerateSetterVisitor extends JavaIsoVisitor
{
private final JavaTemplate setter = template("" +
"public void set#{}(#{} #{}) {\n" +
" this.#{} = #{};\n" +
"}"
).build();
@Override
public J.VariableDeclarations.NamedVariable visitVariable(J.VariableDeclarations.NamedVariable variable, P p) {
if (variable.isField(getCursor()) && variable.getSimpleName().equals(fieldName)) {
getCursor().putMessageOnFirstEnclosing(J.ClassDeclaration.class, "varSetterCursor", getCursor());
}
return super.visitVariable(variable, p);
}
@Override
public J.ClassDeclaration visitClassDeclaration(J.ClassDeclaration classDecl, P p) {
J.ClassDeclaration c = super.visitClassDeclaration(classDecl, p);
Cursor varCursor = getCursor().pollNearestMessage("varSetterCursor");
if (varCursor != null) {
J.VariableDeclarations.NamedVariable var = varCursor.getValue();
c = maybeAutoFormat(c,
c.withTemplate(setter, c.getBody().getCoordinates().lastStatement(),
StringUtils.capitalize(var.getSimpleName()),
TypeUtils.asClass(var.getType()).getClassName(), var.getSimpleName(),
var.getSimpleName(), var.getSimpleName()),
p);
}
return c;
}
}
}