![](/img/trans.png)
[英]how to get the position of a particular string in the editor that is currently opened?
[英]How to get currently opened class in eclipse editor correctly?
我有以下代码,它实际上运行良好:
IJavaElement je = null;
IWorkbenchPart part = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActivePart();
if (part instanceof ContentOutline)
part = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
if (part instanceof IViewPartInputProvider)
{
Object elem = ((IViewPartInputProvider)part).getViewPartInput();
if (elem instanceof IJavaElement)
je = (IJavaElement)elem;
}
但是我得到一个警告:
Discouraged access: The type IViewPartInputProvider is not accessible due to restriction on required library C:\\eclipse\\plugins\\org.eclipse.jdt.ui_3.9.1.v20130820-1427.jar
由于访问内部API,这似乎是一种肮脏的方式。 有一个更好的方法吗?
更新
我发现此代码也可以正常工作,但不会产生任何警告:
IJavaElement je = null;
IWorkbenchPart part = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActivePart();
if (part instanceof ContentOutline)
part = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
je = JavaUI.getEditorInputJavaElement(((IEditorPart)part).getEditorInput());
由于我省略了一些检查,因此我担心如果使用我的插件的人具有不同的eclipse配置,此代码可能会导致运行时错误。 有什么改进建议吗?
getActivePart()
和getActiveEditor()
可能返回空值,所以可能getActiveWorkbenchWindow()
和getActivePage()
但这些都不太可能)。
您必须测试part
以查看它是否是IEditorPart
, getActivePart()
返回的IWorkbenchPart
可能是IViewPart
。
JavaUI.getEditorInputJavaElement()
仅在其中一个Java编辑器为活动编辑器时才有效。 对于可能处于活动状态的许多其他类型的编辑器,它将返回null。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.