我是新来的,抱歉我的英语不好;)。
我尝试使用以下代码在java中加载插件jar:
package testprogramm;
import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.HashSet;
import java.util.Set;
public class TestProgramm {
private static Set<Plugin> plugins = new HashSet<Plugin>();
private static TestProgramm instance = new TestProgramm();
public static void main(String[] args) {
System.out.println("TestProgramm v0.1");
File pluginsDirectory = new File("plugins");
if (pluginsDirectory.exists() && pluginsDirectory.isDirectory()) {
for (File pluginFile : pluginsDirectory.listFiles()) {
if (pluginFile.exists() && pluginFile.isFile() && pluginFile.getName().endsWith(".jar")) {
try {
URL[] urls = new URL[] {pluginFile.toURI().toURL()};
ClassLoader loader = new URLClassLoader(urls);
Class c = loader.loadClass("src." + pluginFile.getName().toLowerCase().replace(".jar", "") + ".Main");
Object pluginObject = c.newInstance();
if (pluginObject instanceof Plugin) {
Plugin plugin = (Plugin) pluginObject;
plugins.add(plugin);
plugin.init(instance);
plugin.onEnable();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
while (true) {
if (true) { //code
break;
}
}
for (Plugin plugin : plugins) {
plugin.onDisable();
}
}
public int getInt() {
return 5;
}
}
插件类:
package testprogramm;
public abstract class Plugin {
protected TestProgramm testProgramm;
protected void init(TestProgramm testProgramm) {
this.testProgramm = testProgramm;
}
public TestProgramm getTestProgramm() {
return testProgramm;
}
public abstract void onEnable();
public abstract void onDisable();
public abstract void onEvent1(String eventInfo);
public abstract void onEvent2(String eventInfo);
public abstract void onEvent3(String eventInfo);
}
插件jar中的类:
package ownplugin;
import testprogramm.Plugin;
public class Main extends Plugin {
@Override
public void onEnable() {
System.out.println("OwnPlugin enabled");
}
@Override
public void onDisable() {
System.out.println("OwnPlugin disabled");
}
@Override
public void onEvent1(String arg0) {
}
@Override
public void onEvent2(String arg0) {
}
@Override
public void onEvent3(String arg0) {
}
}
我得到了这个ClassNotFoundException:
java.lang.ClassNotFoundException: src.ownplugin.Main
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at testprogramm.TestProgramm.main(TestProgramm.java:26)
我该怎么办?怎么了。请帮帮我。
答案 0 :(得分:1)
您似乎正在尝试使用名为src.ownplugin.Main
的类。但是,您的Main
类实际上称为ownplugin.Main
。尝试替换此
Class c = loader.loadClass("src." + pluginFile.getName().toLowerCase().replace(".jar", "") + ".Main");
用这个
Class c = loader.loadClass(pluginFile.getName().toLowerCase().replace(".jar", "") + ".Main");