JDT API 容許其它外掛程式在某些 Java 元素上執行 codeassist 或 codeselect。 容許此項運用的元素會實作 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 Core 選項,以變更完成的行為。
有下列兩個選項可選:
有關如何修改 JDT Core 選項的說明, 請參閱JDT Core 的選項
如果您想以程式設計方式來執行程式碼選擇,
請使用 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。