Nel*_*man 6 java eclipse eclipse-jdt
我正在开发一个Eclipse插件,用于修改用户项目中的Java代码.
基本上这个插件的结果是Java注释被添加到某些方法中,所以
void foo() { ... }
Run Code Online (Sandbox Code Playgroud)
变
@MyAnnotation
void foo() { ... }
Run Code Online (Sandbox Code Playgroud)
除了它看起来不那么像; 新插入的注释的缩进是wack(具体来说,新注释一直到行的左侧).我想对文件进行所有更改,然后以编程方式调用"Correct Indentation".
有谁知道如何做到这一点?我在这里或在JDT论坛中找不到答案,所有看起来相关的类(IndentAction,JavaIndenter)都在内部包中,我不应该使用...
谢谢!
好吧,我想我可能已经找到了我想要的解决方案.猜猜我应该花更多时间在搜索之前...但是为了将来的参考,这就是我的所作所为!好东西在ToolFactory中......
import org.eclipse.jdt.core.ToolFactory;
import org.eclipse.jdt.core.formatter.CodeFormatter;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.text.edits.TextEdit;
import org.eclipse.jdt.core.ICompilationUnit;
...
ICompilationUnit cu = ...
...
CodeFormatter formatter = ToolFactory.createCodeFormatter(null);
ISourceRange range = cu.getSourceRange();
TextEdit indent_edit =
formatter.format(CodeFormatter.K_COMPILATION_UNIT,
cu.getSource(), range.getOffset(), range.getLength(), 0, null);
cu.applyTextEdit(indent_edit, null);
cu.reconcile();
Run Code Online (Sandbox Code Playgroud)
这会重新格式化整个文件.如果您需要重新格式化,还有其他选择......