eclipse-plugin - 重写节点后注释行消失

标签 eclipse-plugin eclipse-jdt automated-refactoring

我正在编写简单的重构,并注意到一件奇怪的事情。我正在重写的节点之前的注释行在重构后消失了。还将相关节点之后的注释转移到节点内部并在新位置打破缩进。这很奇怪,我想问一下这是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;
}

最佳答案

//pre 注释消失,因为解析器认为它是下一个语句(由 node 表示)的一部分,您可以将其替换为 newNode 。当 node 消失时,附加的注释也会消失。

仍在思考为什么//post最终会出现在它原来的位置...尝试在设置其then和else语句之前替换newNode

关于eclipse-plugin - 重写节点后注释行消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13593015/

相关文章:

使用反射进行JAVA重构

eclipse - 在 spring-maven 项目的 eclipse helios 中不显示在服务器上运行选项

eclipse-plugin - 实现 WizardExportResourcesPage 时,如何修改所选资源?

java - 如何同时瞄准朱诺号和开普勒号

没有 JDT 的 Eclipse

eclipse - IntelliJ 喜欢 'Extract Property' 将 Maven Artifact 版本提取到 Eclipse 中的属性

java - Eclipse rcp 类加载器 hell : moved class still visible at compiletime but not at runtime anymore

Eclipse 2019 黑色背景

java - 如何使用 ASTRewrite 将特定的 SimpleType 替换为 PrimitiveType?

java - 将 foreach 重构为 for 循环