我正在开发一个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。
答案 0 :(得分:2)
你是对的。在E4中你应该使用注射。
为了避免使用NPE,可以在部分构造函数中获得对IEclipseContext的引用。
public class MyPart {
private IEclipseContext context;
@Inject
public MyPart(IEclipseContext context) {
this.context = context;
}
}
假设您已在插件中定义了您的part类,并且该类在E4应用程序中被引用为Part,您可以使用其id获取对Part实例的引用
在代码中的某处,您使用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;
}