Java 获取Eclipse编辑器的当前源代码?

Java 获取Eclipse编辑器的当前源代码?,java,eclipse,editor,Java,Eclipse,Editor,我正在使用EclipseIDE。首先,我想开发一个插件,这个插件允许我将整个源代码作为一个简单的字符串 我使用模板“helloworld命令”制作了一个简单的“helloworld”插件。现在我正在搜索Eclipse编辑器中的源代码,并使用System.out.println()显示它;声明,而不是向世界问好 我试过了,但它只显示了我的项目的层次顺序,packageName/src/nameOfClass System.out.println( Workbench.getInstance

我正在使用EclipseIDE。首先,我想开发一个插件,这个插件允许我将整个源代码作为一个简单的字符串

我使用模板“helloworld命令”制作了一个简单的“helloworld”插件。现在我正在搜索Eclipse编辑器中的源代码,并使用System.out.println()显示它;声明,而不是向世界问好

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

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

我的目标是获取类本身的源代码(类{***}的公共类名)。

首先不要使用
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您可以从编辑器中获得样式文本控件,但此代码更通用。不,我想使用
getAdapter()
IEditorPart
上的
,使其适应直接返回内容、编辑输入或文档的内容。一般来说,Eclipse平台的东西鼓励使用Adaptive over instanceof和casts。谢谢大家,但我认为,“IDocument”还有一个问题,似乎我的Eclipse没有导入它,甚至不知道它在等待什么答案:)再次感谢
IDocument
位于
org.Eclipse.text
插件中,所以你必须将它添加到你的插件依赖项中。谢谢大家,但我认为,我的“IDocument”还有另一个问题,似乎我的Eclipse没有导入它,甚至不知道它在等待你的答案:)再次感谢