Eclipse 使用JDT在If else语句中插入块/大括号

Eclipse 使用JDT在If else语句中插入块/大括号,eclipse,eclipse-plugin,eclipse-jdt,Eclipse,Eclipse Plugin,Eclipse Jdt,我正在创建一个Eclipse插件,它应该在一行if-else语句中插入块 [就像Eclipse在保存操作时设置编辑器的首选项一样] 例如 if(isFormed) 如果(i==1) System.out.println(“i为1”); 其他的 System.out.println(“i未定义”); 应替换为 if(isFormed) { 如果(i==1) { System.out.println(“i为1”); } 其他的 { System.out.println(“i未定义”); } }

我正在创建一个Eclipse插件,它应该在一行if-else语句中插入块

[就像Eclipse在保存操作时设置编辑器的首选项一样]

例如

if(isFormed)
如果(i==1)
System.out.println(“i为1”);
其他的
System.out.println(“i未定义”);
应替换为

if(isFormed)
{
如果(i==1)
{
System.out.println(“i为1”);
}
其他的
{
System.out.println(“i未定义”);
}
}
下面是我如何访问和替换AST中的语句

node.accept(新的ASTVisitor(){
@凌驾
公共布尔访问(IfStatement IfStatement){
//如果IfStatemnet不存在,则添加块。
if(ifStatement!=null){
语句thenStatement=ifStatement.getThenStatement();
语句elstatement=ifStatement.getelstatement();
字符串codeToReplace=“if”(“+ifStatement.getExpression()+”);
if(then语句块实例)
codeToReplace+=“\n”+thenStatement+”;
其他的
codeToReplace+=“{\n”+thenStatement+“\n}”;
if(elstatement!=null){
if(块的elseStatement实例)
codeToReplace+=“else”+elseStatement+“\n”;
其他的
codeToReplace+=“else{\n”+elstatement+“\n}”;
}
替换声明(重写器、getBlockInstence(ifStatement)、codeToReplace、ifStatement);
}
返回超级访问(ifStatement);
}
});
&一旦全部访问完毕,我将提交工作副本。 这会将块添加到外部if-else,而不会添加到内部if-else

我还尝试替换文档并在访问时提交,如下所示:

IDocument document=new org.eclipse.jface.text.document(iCompilationUnit.getSource());
TextEdit edits=mCompilationUnit.rewrite(文档,空);
document.replace(ifStatement.getStartPosition()、ifStatement.getLength()、codeToReplace);
编辑、应用(文件);
iCompilationUnit.getBuffer().setContents(document.get());
iCompilationUnit.commitWorkingCopy(true,新的NullProgressMonitor());
但这会在错误的位置为内部if-else和整个代码添加大括号,因为它没有更新要替换的代码的“偏移量”和“长度”&因此它会不断地在错误的位置替换和出错

//void org.eclipse.jface.text.IDocument.replace(int偏移量、int长度、字符串texttobereplace)

我还尝试了解eclipse是如何做到这一点的。但没能达到那一点。
有人能帮我解决这个问题吗?或者我应该参考的任何类型的插件代码?即使我能得到哪个eclipse插件能做到这一点,我也可以尝试反编译它。

我遇到了同样的问题,通过更改表达式的偏移量被更改,而没有更新。作为一种解决方法,我首先收集了所有应该被替换的表达式,然后反转了收集,因此在代码末尾开始了更改。所以偏移量没有改变,我可以改变所有的表达式


这不是一个好的解决方案,但这对我很有效。

您正在访问的
节点
-它是否仅指外部
if else
语句?如何获得
节点
?首先它将访问外部IfStatement,然后访问内部IfStatement。我检索了CompliationUnit的所有类型声明&我访问了所有类型声明。但是,当您提交对外部语句的修改时,对内部语句的引用不是无效的吗?因此,这就像内部语句的引用引用引用了较旧的信息,如偏移量和长度等。它不是更新的。因此,刷新它是否有帮助不知怎么的,是信息吗?