使用 Java 构建插件系统的最佳方法
您将如何为您的 Java 应用程序实现插件系统?
How would you implement a Plugin-system for your Java application?
是否有可能拥有一个易于使用(对于开发人员)的系统,它可以实现以下目标:
Is it possible to have an easy to use (for the developer) system which achieves the following:
- 用户将他们的插件放入应用的子目录中
- 插件可以提供配置屏幕
- 如果您使用框架,许可证是否与商业开发兼容?
推荐答案
首先你需要一个所有插件都需要实现的接口,例如
First you need an interface that all plugins need to implement, e.g.
public interface Plugin {
public void load(PluginConfiguration pluginConfiguration);
public void run();
public void unload();
public JComponent getConfigurationPage();
}
插件作者应该将他们的插件捆绑到 JAR 文件中.您的应用程序打开 JAR 文件,然后可以使用 JAR 清单中的属性或 JAR 文件中所有文件的列表来查找实现插件接口的类.实例化那个类,插件就可以使用了.
Plugin authors should then bundle their plugins into JAR files. Your applications opens the JAR file and could then use an attribute from JAR manifest or the list of all files in the JAR file to find the class that implements your Plugin interface. Instantiate that class, the plugin is ready to go.
当然,您可能还想实现某种沙盒,以限制插件能做什么和不能做什么.我创建了一个小型 测试应用程序(和 blogged about it) 由两个插件组成,其中一个被拒绝访问本地资源.
Of course you may also want to implement some kind of sandboxing so that the plugin is restricted in what it can and can not do. I have created a small test application (and blogged about it) that consists of two plugins, one of which is denied access to local resources.
相关文章