
本文详解在 eclipse rcp 应用中通过编程方式修改“number of opened editors before closing”(即编辑器自动关闭阈值)的合规方法,指出常见错误用法,并提供基于官方扩展点与稳定 api 的替代方案。
本文详解在 eclipse rcp 应用中通过编程方式修改“number of opened editors before closing”(即编辑器自动关闭阈值)的合规方法,指出常见错误用法,并提供基于官方扩展点与稳定 api 的替代方案。
在 Eclipse RCP 应用开发中,控制编辑器标签页数量的行为(例如:当打开编辑器超过一定数量后自动关闭最旧的编辑器)是一个常见需求。该行为由 IDE 的 REUSE_EDITORS 偏好项控制,其实际含义是“最大同时保留的编辑器数量”,超出此值时,系统将自动关闭最早打开的非活动编辑器(而非真正“关闭前提示”)。
⚠️ 需特别注意:你尝试使用的 org.eclipse.editorss.maxEditorTabs 键名并不存在(拼写错误且非标准),而 IWorkbenchPreferenceConstants.MAX_EDITORS_FROM_MODEL 确实已在较新版本 Eclipse(自 4.10+ 起)中被移除,因其属于已废弃的模型驱动编辑器架构。
✅ 正确做法是使用 Eclipse 内部定义的常量 IPreferenceConstants.REUSE_EDITORS,但必须通过 WorkbenchPlugin.getDefault().getPreferenceStore() 获取偏好存储对象——这是唯一能影响工作台级编辑器复用逻辑的偏好存储实例:
import org.eclipse.ui.internal.IPreferenceConstants;
import org.eclipse.ui.internal.WorkbenchPlugin;
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
import org.eclipse.core.runtime.preferences.InstanceScope;
import org.osgi.service.prefs.Preferences;
// ✅ 推荐:在 Workbench 启动早期(如 WorkbenchAdvisor#preStartup() 或 Plugin#start() 中)
IEclipsePreferences prefs = WorkbenchPlugin.getDefault().getPreferenceStore();
prefs.putInt(IPreferenceConstants.REUSE_EDITORS, 15); // 设置为 15 个编辑器上限
// 若需持久化到磁盘(推荐)
try {
prefs.flush(); // 注意:flush() 已足够,无需强制转型为 IPersistentPreferenceStore
} catch (BackingStoreException e) {
// 处理持久化失败
Activator.logError("Failed to save editor reuse preference", e);
}? 关键要点总结:
REUSE_EDITORS 是整型偏好项(int),默认值通常为 10;
必须使用 WorkbenchPlugin.getDefault().getPreferenceStore(),而非 getPreferenceStore()(后者返回插件自身作用域的存储,对工作台行为无效);
IPreferenceConstants 和 WorkbenchPlugin 属于 internal API,虽当前可用,但不保证向后兼容。生产环境建议封装调用,并在升级 Eclipse 版本时重点验证;
-
更健壮的替代方案是通过 plugin.xml 声明式配置(适用于静态设定):
<extension point="org.eclipse.core.runtime.preferences"> <initializer class="com.example.MyPreferenceInitializer"/> </extension>并在 MyPreferenceInitializer#initializeDefaultPreferences() 中调用 prefs.setDefault(IPreferenceConstants.REUSE_EDITORS, 15);
修改后需重启工作台或重新打开编辑器才能完全生效(部分设置支持运行时热更新,但 REUSE_EDITORS 通常需新编辑器实例触发逻辑)。
综上,虽然该偏好项无公开的稳定 API 封装,但通过 WorkbenchPlugin + IPreferenceConstants.REUSE_EDITORS 组合仍是当前 Eclipse 平台下最可靠、最广泛验证的编程设置方式。务必避免硬编码字符串键名,并始终以 flush() 替代已弃用的 save() 调用。










