【问题标题】:How to get workbench/view in Eclipse (e4)?如何在 Eclipse (e4) 中获取工作台/视图?
【发布时间】:2016-03-27 15:59:06
【问题描述】:

我正在开发一个需要访问视图的 Eclipse 插件。

我找到了这种获取工作台的方法,但我猜它只在 Eclipse 3.x 中有效,而我使用的是 Eclipse 4,所以它不起作用:

IWorkbench workbench = PlatformUI.getWorkbench();
IViewPart part = workbench.getActiveWorkbenchWindow().getActivePage()
            .findView("id_of_the_view");

然后我发现是这样的:

@Inject
private static EPartService epartService;

MPart mPart = epartService.findPart("id_of_the_view");
    MyViewClass part = (MyViewClass)mPart.getObject();

抛出 NullPointerException。我已确保视图已打开。

我错过了什么?

编辑:

我也试过这个,发现here (german)

 @Inject
 private static EPartService epartService;
 @Inject
 private static MApplication application;   
 @Inject
 private static EModelService modelService;
 ...
MUIElement element = modelService.find("id_of_the_view", application);
    if(element instanceof MPart) {
        MPart part = (MPart) element;
...
}

但我在 .find() 行中也有一个 NPE。

【问题讨论】:

  • 使用EPartService 是正确的。什么是 null - mPart 或 epartService?你确定 id 是正确的吗?
  • 不要将static 用于注入对象。你在哪里运行这段代码?
  • 仅注入由 Eclipse 从 Application.e4xmi 中描述的对象创建的类。如果您使用new 创建一个类,它不会被注入。
  • 看起来您仍在使用 3.x 兼容模式,因此您不应该尝试使用注入。在这种情况下,PlatformUI 是正确使用的东西 - 但它必须作为 Eclipse 插件的一部分在正确初始化的 Eclipse 中运行。
  • 您的代码必须在 Eclipse 插件中。

标签: eclipse view e4 workbench


【解决方案1】:

你是对的。在 E4 中,您应该使用注入。

为避免 NPE,您可以在部分构造函数中获取对 IEclipseContext 的引用。

public class MyPart {
    private IEclipseContext context;

    @Inject
    public MyPart(IEclipseContext context) {
        this.context = context;
    }

}

假设您在插件中定义了部件类,并且该类在 E4 应用程序中被引用为部件,您可以使用部件 id 获取对部件实例的引用

在您的代码中的某处,您使用 id 来获取您的部分的实例

// somewhere in your code ..
// (where you can access the context instance)
MPart myPart = getPart(context, "com.example.myPart");

简单的方法是使用 EPartService.findPart() ,如下:

/** with this method I can get reference to the part */
public static MPart getPart(IEclipseContext context, String partId) {
    EPartService partService = context.get(EPartService.class);
    MPart part = partService.findPart(partId);
    return part;
}

注意静态方法。上下文对象和静态成员不是朋友!!

对于多个匹配或高级搜索,您可以使用 EPartService.findElements(),如下所示:

    public static List<MPart> getParts(IEclipseContext context,
        MWindow workbenchWindow, String partId) {

        EPartService partService = context.get(EPartService.class);
        EModelService modelService = context.get(EModelService.class);
        List<MPart> parts =
                modelService.findElements(workbenchWindow, partId, MPart.class,
                        null, EModelService.OUTSIDE_PERSPECTIVE
                                | EModelService.IN_ANY_PERSPECTIVE
                                | EModelService.IN_SHARED_AREA);
        return parts;
    }

【讨论】:

  • 您好,感谢您的意见。这听起来很有趣,我一定会复习的。但正如在 cmets 中看到的那样,我使用的是 3.x 而不是 E4,所以在没有所有这些东西的情况下问题很容易解决。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-30
  • 1970-01-01
  • 1970-01-01
  • 2016-08-04
相关资源
最近更新 更多