我正在撰寫一個 Eclipse 插件,它根據所選 java 檔案的內容(右鍵單擊 -> 自定義選單項)重寫 java 檔案(可能是多個檔案)。
一切都按預期作業,但檔案的重寫并不能管理內容格式,因此在使用插件后,我必須使用 Eclipse 格式操作手動格式化每個受影響的 java 檔案。
我能夠以編程方式對選定的 java 檔案呼叫 Eclipse 格式操作,但我還想格式化所有其他檔案。
這是我現在所擁有的(應該更改的部分在 for 回圈內):
@Override
public Object execute(ExecutionEvent event) throws ExecutionException
{
var workbench = PlatformUI.getWorkbench();
var activeWorkbenchWindow = workbench.getActiveWorkbenchWindow();
var selection = activeWorkbenchWindow.getActivePage().getSelection();
List<String> generatedClasses = null;
if ((selection instanceof IStructuredSelection structuredSelection)
&& (structuredSelection.getFirstElement() instanceof ICompilationUnit compilationUnit))
{
try
{
var projectClassLoader = getProjectClassLoader(compilationUnit.getJavaProject());
generatedClasses = bindingGenerator.generateBindings(compilationUnit, projectClassLoader);
}
catch (ClassNotFoundException | NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException | IOException
| IllegalClassFormatException | JavaModelException e)
{
// TODO pop an error message dialog?
return null;
}
for (String generatedClass : generatedClasses)
try
{
// I can find the IType of each affected java file here if it should help?
var type = compilationUnit.getJavaProject().findType(generatedClass);
// This is where the formating should be made. The code below currently format the selected file only.
var commandId = IJavaEditorActionDefinitionIds.FORMAT;
var handlerService = workbench.getService(IHandlerService.class);
try
{
handlerService.executeCommand(commandId, null);
}
catch (Exception e1)
{
e1.printStackTrace();
}
}
catch (JavaModelException e)
{
e.printStackTrace();
}
}
MessageDialog.openInformation(activeWorkbenchWindow.getShell(), "Generated bindings on files:", String.join(", ", generatedClasses));
return null;
}
uj5u.com熱心網友回復:
感謝 @greg-449 向我指出 ToolFactory.createCodeFormatter。
我只需要使用專案的選項創建一個格式化程式,如下所示:
ToolFactory.createCodeFormatter(compilationUnit.getJavaProject().getOptions(true));
然后在檔案的源上使用格式化程式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/407878.html
標籤:
上一篇:如何為不在根目錄上服務的Tomcatwebapp提供favicon以避免瀏覽器在/favicon.ico上出現404
