我的回答是基於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);
工程就像一個魅力! – bellpeace