io.slugstack.rewritejavarecipes.GenerateGetter 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 GenerateGetter extends Recipe {
private final String fieldName;
@Override
public String getDisplayName() {
return "Generate getter";
}
@Override
public String getDescription() {
return "Generate getter method for a given class field.";
}
@Override
protected TreeVisitor, ExecutionContext> getVisitor() {
return new GenerateGetterVisitor<>();
}
private class GenerateGetterVisitor extends JavaIsoVisitor
{
private final JavaTemplate getter = template("" +
"public #{} get#{}() {\n" +
" return #{};\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, "varCursor", 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("varCursor");
if (varCursor != null) {
J.VariableDeclarations.NamedVariable var = varCursor.getValue();
c = maybeAutoFormat(c,
c.withTemplate(getter, c.getBody().getCoordinates().lastStatement(),
TypeUtils.asClass(var.getType()).getClassName(),
StringUtils.capitalize(var.getSimpleName()),
var.getSimpleName()),
p);
}
return c;
}
}
}