JDT API 允许其它插件对一些 Java 元素执行“代码辅助”或“代码选择”。允许此处理的元素实现 ICodeAssist。在 Java 模型中,有两个元素实现此接口:IClassFile 和 ICompilationUnit。
有两种处理方法:
注意:仅当类文件具有相连接的源时,完成和选择才回答该类文件的结果。
使用程序执行代码完成的唯一方法是使用 ICodeAssist.codeComplete。指定在单元中完成的位置,并提供 ICompletionRequestor 的实例来接受可能的完成。
每种建议都被请求者的一种方法接受。这些方法的参数描述元素(名称、参数和声明类型等等)、元素的位置以及当前上下文中的建议的相关性。
当您对所有结果类型都不感兴趣时,执行代码完成的简单方法是使用 CompletionRequestorAdapter。
// Get the compilation unit
ICompilationUnit unit = ...;
// Get the offset
int offset = ...;
// Create the requestor
ICompletionRequestor requestor = new CompletionRequestorAdapter() {
public void acceptClass(
char[] packageName,
char[] className,
char[] completionName,
int modifiers,
int completionStart,
int completionEnd,
int relevance) {
System.out.println("propose a class named " + new String(className));
}
};
// Compute proposals
unit.codeComplete(offset, requestor);
其它插件可以更改代码完成的选项。可以修改“JDT 核心”选项来更改完成行为。
有两个选项:
要了解如何修改“JDT 核心”选项,参见:什么是“JDT 核心”选项?
如果想要使用程序执行代码选择,则使用的方法是 ICodeAssist.codeSelect。使用此方法需要知道选择的起始位置和长度。结果是 Java 元素的数组。大多数时候,数组中只有一个元素,但是如果选择是有歧义的,则会返回所有可能的元素。
// Get the compilation unit
ICompilationUnit unit = ...;
// Get the offset and length
int offset = ...;
int length = ...;
// perform selection
IJavaElement[] elements = unit.codeSelect(offset, length);
System.out.println("the selected element is " + element[0].getElementName());
如果选择的长度等于 0,则使用完整的封装标记来计算选择。
public void fooMethod(Object) { }当偏移量在 fooMethod 的第一个字符之后,且长度为 0 时,选择是 fooMethod。但是,如果长度为 5,则选择是 ooMet。