我正在尝试重构旧的SimpleFormController。我想用实际的成功视图和表单视图字符串代替getSuccessView()和gerFormView()调用。
我浏览了https://spoon.gforge.inria.fr/first_transformation.html,它展示了如何生成和添加语句,但是我不明白如何修改。
我已经试过了。
用getSuccessView()和getFormView()调用替换语句
public class SimpleFormControllerReplaceViewCall extends AbstractProcessor<CtMethod> {
MetaData meta;
String successView= "successView";
String formView = "formView";
public SimpleFormControllerReplaceViewCall(MetaData meta) {
this.meta = meta;
}
@Override
public boolean isToBeProcessed(CtMethod candidate) {
if(candidate.getBody() == null) { //Ignore abstract methods
return false;
}
String sourceCode;
try {
sourceCode = candidate.getBody()
.getOriginalSourceFragment()
.getSourceCode();
} catch (Exception e) {
return false;
}
return sourceCode.contains(getViewFunctionName(successView))
|| sourceCode.contains(getViewFunctionName(formView));
}
@Override
public void process(CtMethod method) {
Node beanNode = getBeanNode(method);
CtBlock<Object> body = getFactory().createBlock();
method.getBody().getStatements()
.stream()
.map(s -> {
Optional<String> sourceCode = getStatementSourceCode(s);
if(!sourceCode.isPresent()) {
return s.clone(); // Clone required to handle runtime error for trying attach a node to two parents
} else {
System.out.println("Modifying: " + method.getSignature());
String code = sourceCode.get();
code = replaceViewCalls(beanNode, code, successView);
code = replaceViewCalls(beanNode, code, formView);
return getFactory().createCodeSnippetStatement(code);
}
}).forEach(body::addStatement);
method.setBody(body);
}
private Optional<String> getStatementSourceCode(CtStatement s) {
String sourceCode = null;
try {
sourceCode = s.getOriginalSourceFragment()
.getSourceCode();
} catch (Exception e) {}
System.out.println(sourceCode);
if (sourceCode != null &&
(sourceCode.contains(getViewFunctionName(successView))
|| sourceCode.contains(getViewFunctionName(formView)))) {
sourceCode = sourceCode.trim();
if(sourceCode.endsWith(";"))
sourceCode = sourceCode.substring(0, sourceCode.length()-1);
return Optional.of(sourceCode);
} else {
return Optional.empty();
}
}
public String replaceViewCalls(Node beanNode, String code, String viewType) {
String getViewFunctionName = getViewFunctionName(viewType);
if (!code.contains(getViewFunctionName)) {
return code;
}
String view = AppUtil.getSpringBeanPropertyValue(beanNode, viewType);
return code.replaceAll(getViewFunctionName + "\(\)", String.format(""%s"", view));
}
public Node getBeanNode(CtMethod method) {
String qualifiedName = method.getParent(CtClass.class).getQualifiedName();
return meta.getFullyQualifiedNameToNodeMap().get(qualifiedName);
}
private String getViewFunctionName(String viewType) {
return "get" + viewType.substring(0, 1).toUpperCase() + viewType.substring(1);
}
}
然而,这增加了不必要的块结束if(){…};当if {} else{}块包含返回语句时,这会产生语法错误。当有多个同名的类时(例如,Map存在于几个库的类路径中),自动导入将被打开,并且不会添加导入—这与文档一致。在重构代码时可以避免这种情况吗?原始java文件有正确的导入。
我尝试的另一种方法是直接操纵整个身体。
@Override
public void process(CtMethod method) {
String code = method.getBody()
.getOriginalSourceFragment()
.getSourceCode();
Node beanNode = getBeanNode(method);
code = replaceViewCalls(beanNode, code, successView);
code = replaceViewCalls(beanNode, code, formView);
CtCodeSnippetStatement codeStatement = getFactory().createCodeSnippetStatement(code);
method.setBody(codeStatement);
}
这仍然有相同的自动导入问题,作为第一个。除此之外,它还添加了多余的花括号,例如
void method() { x=y;}
将成为
void method() { {x=y;} }
那当然会印得很漂亮。
也为getOriginalSourceFragment() javadocs也有下面的警告
警告:这是一个高级方法,不能被视为一部分稳定API
我想做的另一件事是为getSuccessView()的每种使用类型创建模式viewName = getSuccessView();返回getSuccessView ();返回ModelAndView(getSuccessView(), map);等等,但是为此我将不得不编写一大堆处理器/模板。
因为它是一个简单的替换,最简单的是在
下面做类似的事情//Walk over all files and execute
Files.lines(Paths.get("/path/to/java/file"))
.map(l -> l.replaceAll("getSuccessView\(\)", "actualViewNameWithEscapedQuotes"))
.map(l -> l.replaceAll("getFormView\(\)", "actualViewNameWithEscapedQuotes"))
.forEach(l -> {
//write to file
});
既然我可以在spoon的帮助下避免文本操作,比如改变修饰符、注释、方法名、注释等,我希望应该有一个更好的方法来修改方法体。
您应该将处理器输入视为抽象语法树而不是字符串:
public class SimpleFormControllerReplaceViewCall extends AbstractProcessor<CtMethod<?>> {
@Override
public boolean isToBeProcessed(CtMethod candidate) {
if(candidate.isAbstract()) { //Ignore abstract methods
return false;
}
return !candidate.filterChildren((CtInvocation i)->
i.getExecutable().getSimpleName().equals("getSuccessView")
|| i.getExecutable().getSimpleName().equals("getFormView")).list().isEmpty();
}
@Override
public void process(CtMethod<?> ctMethod) {
Launcher launcher = new Launcher();
CodeFactory factory = launcher.createFactory().Code();
List<CtInvocation> invocations = ctMethod.filterChildren((CtInvocation i)->
i.getExecutable().getSimpleName().equals("getSuccessView")
|| i.getExecutable().getSimpleName().equals("getFormView")).list();
for(CtInvocation i : invocations) {
if(i.getExecutable().getSimpleName().equals("getSuccessView")) {
i.replace(factory.createLiteral("successView"));
} else {
i.replace(factory.createLiteral("formView"));
}
}
}
}
这里遍历CtMethod AST以搜索具有指定属性的CtInvocation元素。然后用新的字符串字面值元素替换找到的元素。