All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.slugstack.rewritejavarecipes.FieldAccessToGetterVisitor Maven / Gradle / Ivy

There is a newer version: 0.2.2
Show newest version
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;
import org.openrewrite.java.tree.TypeUtils;

public class FieldAccessToGetterVisitor

extends JavaVisitor

{ private final JavaTemplate getTemplate = template("#{}.get#{}()").build(); private final JavaType.FullyQualified declaringClass; private final String fieldName; /** * Just a note to future-self: keep these parameters in mind while * mentally-digesting what we're trying to do here. *

* These parameters refer to the specific field and the class the specific field * is defined in. When we're visiting nodes, we're evaluting whether we should * modify anything as part of traversing to these other AST nodes (input params * on overrides). * * @param declaringClass class context the field is defined in * @param fieldName field we're "updating" to use getter */ public FieldAccessToGetterVisitor(String declaringClass, String fieldName) { this.declaringClass = JavaType.Class.build(declaringClass); this.fieldName = fieldName; } @Override public J visitFieldAccess(J.FieldAccess fieldAccess, P p) { J j = super.visitFieldAccess(fieldAccess, p); J.FieldAccess asFieldAccess = (J.FieldAccess) j; if (asFieldAccess.getTarget() instanceof J.Identifier && matchesClass(asFieldAccess.getTarget().getType()) && asFieldAccess.getSimpleName().equals(fieldName) && !(getCursor().dropParentUntil(J.class::isInstance).getValue() instanceof J.Assignment) ) { j = maybeAutoFormat(j, j.withTemplate(getTemplate, asFieldAccess.getCoordinates().replace(), ((J.Identifier) asFieldAccess.getTarget()).getSimpleName(), StringUtils.capitalize(asFieldAccess.getSimpleName()) ), p); } return j; } private boolean matchesClass(JavaType test) { JavaType.Class testClassType = TypeUtils.asClass(test); return testClassType != null && testClassType.getFullyQualifiedName().equals(declaringClass.getFullyQualifiedName()); } }





© 2015 - 2024 Weber Informatics LLC | Privacy Policy