io.slugstack.rewritejavarecipes.FieldAccessToSetterVisitor Maven / Gradle / Ivy
Show all versions of rewrite-java-recipes Show documentation
package io.slugstack.rewritejavarecipes;
import org.openrewrite.internal.StringUtils;
import org.openrewrite.java.JavaTemplate;
import org.openrewrite.java.JavaVisitor;
import org.openrewrite.java.tree.J;
import org.openrewrite.java.tree.JavaType;
public class FieldAccessToSetterVisitor extends JavaVisitor
{
private final JavaTemplate setterTemplate = template("#{}.set#{}(#{})").build();
private final JavaType.FullyQualified declaringClass;
private final String fieldName;
public FieldAccessToSetterVisitor(String declaringClass, String fieldName) {
this.declaringClass = JavaType.Class.build(declaringClass);
this.fieldName = fieldName;
}
@Override
public J visitAssignment(J.Assignment assign, P p) {
J j = visitAndCast(assign, p, super::visitAssignment);
J.Assignment asAssign = (J.Assignment) j;
if (asAssign.getVariable() instanceof J.FieldAccess &&
!isThis((J.FieldAccess) asAssign.getVariable()) &&
((J.FieldAccess) asAssign.getVariable()).getSimpleName().equals(fieldName)
) {
// @formatter:on
j = maybeAutoFormat(j,
j.withTemplate(setterTemplate,
asAssign.getCoordinates().replace(),
((J.FieldAccess) asAssign.getVariable()).getTarget(),
StringUtils.capitalize(((J.FieldAccess) asAssign.getVariable()).getSimpleName()),
asAssign.getAssignment()
), p, getCursor().getParentOrThrow());
// @formatter:on
}
return j;
}
private boolean isThis(J.FieldAccess f) {
return ((J.Identifier) f.getTarget()).getSimpleName().equals("this");
}
}