如何在自行维护的Eclipse插件中检测其他已安装插件是否存在
提问:Eclipse插件内检测其他插件是否安装的优雅实现方案
我正在维护一款Eclipse插件,需要在该插件内部检测另一款插件是否已安装,查阅该主题下的其他相关问题后,发现该需求的实现难度较高。
我需要检测的目标插件提供了一个view,目前如下代码可以实现需求,但我希望找到更简洁优雅的实现方案:
public static boolean internalPluginInstalled() { IExtensionRegistry reg = Platform.getExtensionRegistry(); IExtensionPoint point = reg.getExtensionPoint("org.eclipse.ui.views"); IExtension[] extensions = point.getExtensions(); for(IExtension extension : extensions) { IConfigurationElement[] configs = extension.getConfigurationElements(); for (IConfigurationElement config : configs) { if (config.getName().equals("view") && config.getAttribute("id").equals("view.id.goes.here")) { return true; } } } return false; }
回答
方案1:直接查询插件Bundle(推荐)
如果已知目标插件的唯一标识(即MANIFEST.MF中定义的Bundle-SymbolicName),可以直接使用平台提供的Bundle查询接口,性能最高且不依赖UI组件,后台线程也可正常调用:
import org.eclipse.core.runtime.Platform; import org.osgi.framework.Bundle; public static boolean isTargetPluginInstalled(String pluginId) { Bundle bundle = Platform.getBundle(pluginId); // 若仅需要判断是否安装,不校验可用状态,直接返回bundle != null即可 return bundle != null && bundle.getState() >= Bundle.RESOLVED; }
方案2:通过View注册表查询(仅已知View ID时使用)
如果只知道目标插件提供的View ID,不需要手动遍历扩展点,可直接使用Eclipse UI提供的View注册表接口,写法更简洁:
import org.eclipse.ui.PlatformUI; import org.eclipse.ui.views.IViewDescriptor; public static boolean isTargetViewExists(String viewId) { if (!PlatformUI.isWorkbenchRunning()) { return false; } IViewDescriptor targetView = PlatformUI.getWorkbench().getViewRegistry().find(viewId); return targetView != null; }
方案对比
- 方案1是通用最优解,执行效率远高于遍历扩展点的实现,适用所有场景
- 方案2比原实现简洁,但只能在Workbench启动完成后调用,不可用于早于UI启动的后台逻辑
内容的提问来源于stack exchange,提问作者Dave Carpeneto
相关产品推荐
相关产品推荐

