【问题标题】:Get the current source code of an Eclipse editor?获取 Eclipse 编辑器的当前源代码?
【发布时间】:2015-02-21 23:38:19
【问题描述】:

我正在使用 Eclipse IDE。我想首先开发一个插件,这个插件可以让我把整个源代码作为一个简单的字符串来获取。

我使用模板“hello world command”制作了一个简单的“hello the world”插件。现在我正在搜索从 Eclipse 的编辑器中获取源代码并使用 System.out.println(); 显示它。声明而不是显示 HELLO THE WORLD。

我试过了,但它只显示了我的项目的层次顺序,packageName/src/nameOfClass。

System.out.println(
    Workbench.getInstance().getActiveWorkbenchWindow().getActivePage().getActiveEditor().getEditorInput() 
);

我的目标是获取类本身的源代码(public class nameOfClass{ *** })。

【问题讨论】:

  • 谢谢大家,但我认为,我的“IDocument”还有另一个问题,似乎我的 Eclipse 没有导入它,甚至知道它在等待您的回答 :) 再次感谢

标签: java eclipse editor


【解决方案1】:

首先不要使用Workbench这是一个内部类,不能使用。使用PlatformUI 获取工作台。

IEditorPart editor = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();

if (editor instanceof ITextEditor)
 {
   ITextEditor textEditor = (ITextEditor)editor;

   IDocumentProvider provider = textEditor.getDocumentProvider();

   IEditorInput input = editor.getEditorInput();

   IDocument document = provider.getDocument(input);

   String text = document.get();

   ...
 }

注意:并非所有编辑器都是文本编辑器,因此需要检查(上面的 ITextEditor 实例检查)。

【讨论】:

  • 把IEditorPart改成可以提供内容的东西不是更好吗?我面前没有 Eclipse SDK,所以我不知道界面编辑器通常可以适应什么,但我记得过去做过类似的事情。
  • @E-Riz 您可以从编辑器中获取样式文本控件,但此代码更通用。
  • 不,我正在考虑在IEditorPart 上使用getAdapter() 以使其适应直接返回内容、EditorInput 或文档的内容。一般来说,Eclipse 平台的东西鼓励使用 Adaptable 而不是 instanceof 和 casts。
  • 谢谢大家,但我认为,我的“IDocument”还有另一个问题,好像我的 Eclipse 没有导入它,甚至知道它在等待您的回答 :) 再次感谢
  • IDocument 在 org.eclipse.text 插件中,因此您必须将其添加到插件依赖项中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-15
  • 1970-01-01
  • 2011-07-18
  • 1970-01-01
  • 2014-07-20
  • 2014-09-15
  • 2021-12-27
相关资源
最近更新 更多