如何以编程方式在插件处理程序中的特定 java 文件上调用 Eclipse 格式?

How to programmatically call Eclipse format on a specific java file within a plugin handler?

我正在编写一个 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;
}

感谢@greg-449 指出我 ToolFactory.createCodeFormatter。

我只需要创建一个带有项目选项的格式化程序,如下所示:

ToolFactory.createCodeFormatter(compilationUnit.getJavaProject().getOptions(true));

然后在文件源上使用格式化程序。