要创建可插入的Java程序,您需要遵循以下步骤:
public interface Plugin {
void execute();
}
public class PluginA implements Plugin {
@Override
public void execute() {
System.out.println("Plugin A is executing.");
}
}
public class PluginB implements Plugin {
@Override
public void execute() {
System.out.println("Plugin B is executing.");
}
}
public class Main {
public static void main(String[] args) {
Plugin pluginA = new PluginA();
Plugin pluginB = new PluginB();
pluginA.execute();
pluginB.execute();
}
}
public class PluginLoader {
public static void loadPlugins(String pluginDirectory) {
File directory = new File(pluginDirectory);
if (!directory.isDirectory()) {
System.out.println("Plugin directory not found.");
return;
}
File[] files = directory.listFiles();
for (File file : files) {
if (file.isFile() && file.getName().endsWith(".jar")) {
try {
URL[] urls = new URL[] { file.toURI().toURL() };
ClassLoader classLoader = new URLClassLoader(urls);
Class<?> pluginClass = classLoader.loadClass("Plugin");
Plugin plugin = (Plugin) pluginClass.newInstance();
plugin.execute();
} catch (Exception e) {
System.out.println("Error loading plugin: " + e.getMessage());
}
}
}
}
}
请注意,这只是创建可插入Java程序的基本方法。在实际应用程序中,您可能需要考虑更多的细节,例如插件的配置、安全性和性能。
领取专属 10元无门槛券
手把手带您无忧上云