我正在编写简单的重构,并注意到一件奇怪的事情。我正在重写的节点之前的注释行在重构后消失了。有问题的节点之后的注释也会在节点内部传输并在新位置打破缩进。这很奇怪,我想问一下这是jdt中的错误还是我做错了什么并且忘记了。
例如,我的代码假设以最短分支首先出现的方式重构 if-else 语句。当我尝试重构这个时:
// pre
if(a==6) {
a = 5;
return false;
} else {
a++;
}
//post
我明白了:
if (!(a==6)) {
a++;
}
//post
else {
a = 5;
return false;
}
重构完成的相关片段:
protected ASTRewrite createRewrite(CompilationUnit cu, SubProgressMonitor pm) {
pm.beginTask("Creating rewrite operation...", 1);
final AST ast = cu.getAST();
final ASTRewrite rewrite = ASTRewrite.create(ast);
cu.accept(new ASTVisitor() {
public boolean visit(IfStatement node) {
if (node.getStartPosition() > selection.getOffset() + selection.getLength() || node.getStartPosition() < selection.getOffset())
return true;
if (node.getElseStatement() == null)
return true;
int thenCount = countNodes(node.getThenStatement());
int elseCount = countNodes(node.getElseStatement());
if(thenCount <= elseCount)
return true;
IfStatement newnode = ast.newIfStatement();
PrefixExpression neg = negateExpression(ast, rewrite, node.getExpression());
newnode.setExpression(neg);
newnode.setThenStatement((org.eclipse.jdt.core.dom.Statement) rewrite.createMoveTarget(node.getElseStatement()));
newnode.setElseStatement((org.eclipse.jdt.core.dom.Statement) rewrite.createMoveTarget(node.getThenStatement()));
rewrite.replace(node, newnode, null);
return true;
}
});
pm.done();
return rewrite;
}