如何在java中编写自己的插件加载器?

如何在我的java程序中实现插件工具?

我正在使用Java。 我当前的项目是与通用电子硬件相关的东西,它具有自定义命令集。

现在有一个通用的GUI,人们可以通过它访问硬件。 硬件在不同环境中以不同方式运行,即针对不同客户端。 现在的问题是GUI必须能够添加插件。 插件意味着,它必须能够为拥有该特权的客户提供特定设施。 从客户方面来说,添加插件非常简单,只需单击按钮即可添加特定工具。

我考虑插件的原因是,只有在交付核心产品后才会引入越来越多的设施。

您需要提供以下内容:

  • 创建一个API,插件可用于更改/扩展程序的行为(恕我直言,这是最棘手的部分)
  • 定义插件的公共条目,例如,定义插件的入口点或扩展点的插件特定属性文件(实现接口的插件类的类名)
  • 从您选择的位置动态加载插件,例如,来自特定目录的所有* .jar文件(请查看URLClassLoader

API建议:

  • 更喜欢接口而不是(抽象)类
  • 帮助用户快速查看她可以实现哪些接口(例如IAction ,注意领先的I )以及应用程序为插件使用提供的接口(例如WindowManager )可能很有用

您可以随时向应用程序添加jar或插件。 你没有必要做任何特别的事情来实现这一目标。

如果您使用OGSi,您可以更轻松地管理它,支持同一个jar的多个版本,并在应用程序运行时将其删除。 我建议看看Apache Karaf + iPOJO

在任何面向对象语言中实现插件的主要思想是定义插件和相关类必须实现的一组公共接口,然后通过reflection加载和实例化它们……

您可以使用抽象工厂模式,以便插件所需的任何对象都可以实例化…

假设您的插件架构只有3个接口,每个插件必须提供实现这些接口的类,那么您的插件架构可能是这样的:

 public interface PluginInterfaceA { //Define API here }; public interface PluginInterfaceB { // Define API here }; public interface PluginInterfaceC { // Define API here }; public interface PluginFactory { /** * Creates plugin A object. */ PluginInterfaceA createPluginA(); /** * Creates plugin B object. */ PluginInterfaceB createPluginB(); /** * Creates plugin C object. */ PluginInterfaceC createPluginC(); }; 

然后让插件在XML文件或属性文件中定义插件的插件工厂的类名:

例如,假设你的插件定义了:

 package com.my.plugin; public class PluginAImpl implements PluginInterfaceA { // Code for the class }; public class PluginBImpl implements PluginInterfaceB { // Code for the class }; public class PluginCImpl implements PluginInterfaceC { // Code for the class }; public class PluginFactoryImpl implements PluginFactory { public PluginInterfaceA createPluginA() { return new PluginAImpl(); } public PluginInterfaceB createPluginB() { return new PluginAImpl(); } public PluginInterfaceC createPluginC() { return new PluginAImpl(); } }; 

然后在插件plugin.factory.class = com.my.plugin.PluginFactoryImpl的plugin.jar中提供的属性文件// File plugin.properties中定义;

在你的应用程序可以做到

 Properties properties = new Properties(); properties.load(this.getClass().getClassLoader().getResourceAsStream("plugin.properties")); String factoryClass = properties.get("plugin.factory.class"); PluginFactory factory = Class.forName(factoryClass); PluginInterfaceA interfaceA = factory.createPluginA(); PluginInterfaceB interfaceB = factory.createPluginB(); PluginInterfaceC interfaceC = factory.createPluginC(); 

//这里根据您的意愿调用创建的类。

谢谢巴勃罗

JAR文件格式有自己的用于管理插件的小系统 ,用于Java SE的几个部分,包括JDBC驱动程序管理。 只需定义一个服务接口,将带有实现的JAR文件放在类路径上,然后使用ServiceLoader.load加载实现。