我的回答是基于 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);