私の答えはjeeeyulの答えに基づいています。違いは、テンプレート自体だけでなく、それを自動的に解決して追加するためのインポートも必要だったことです。これは、JDTのものを使用して、次の方法で実行できます。
AbstractTextEditor activeEditor =
(AbstractTextEditor) HandlerUtil.getActiveEditor(event);
if (activeEditor == null) {
return null;
}
ITypeRoot element = EditorUtility.getEditorInputJavaElement(activeEditor, true);
if (element == null) {
return null;
}
ICompilationUnit unit = element.getAdapter(ICompilationUnit.class);
if (unit == null) {
return null;
}
ISourceViewer sourceViewer = (ISourceViewer) activeEditor.getAdapter(ITextOperationTarget.class);
Point range = sourceViewer.getSelectedRange();
// You can generate template dynamically here!
Template template = new Template("new List", "Add new list creation", JavaContextType.ID_STATEMENTS,
"List<${type}> ${name:newName(java.util.List)} = new ArrayList<${type}>();${:import(java.util.List, java.util.ArrayList)}",
true);
IRegion region = new Region(range.x, range.y);
JavaContextType contextType = new JavaContextType();
contextType.setId(JavaContextType.ID_STATEMENTS); //Set context type, for which we apply this template
contextType.addResolver(new ImportsResolver("import","import")); //Add imports resolver if we want imports to be added automatically for some template
CompilationUnitContext ctx = new JavaContext(contextType, sourceViewer.getDocument(), range.x,
range.y, unit);
TemplateProposal proposal = new TemplateProposal(template, ctx, region, null);
proposal.apply(sourceViewer, (char) 0, 0, 0);