我正在为我的Java应用程序编写一个插件系统。我的问题是如果我尝试从子类转换到我的父接口
我得到了ClassCastException java.lang.ClassCastException: net.scrumplex.testplugin.Main cannot be cast to net.scrumplex.sprummlbot.plugins.SprummlPlugin
我的界面:
package net.scrumplex.sprummlbot.plugins;
import com.github.theholywaffle.teamspeak3.api.event.BaseEvent;
import com.github.theholywaffle.teamspeak3.api.event.TS3EventType;
public interface SprummlPlugin {
public boolean init(String version);
public void end();
public void handleEvent(TS3EventType type, BaseEvent event);
}
我的TestPlugin:
package net.scrumplex.testplugin;
import com.github.theholywaffle.teamspeak3.api.event.BaseEvent;
import com.github.theholywaffle.teamspeak3.api.event.TS3EventType;
import net.scrumplex.sprummlbot.plugins.SprummlPlugin;
public class Main implements SprummlPlugin {
@Override
public void end() {
System.out.println("Stopped");
}
@Override
public void handleEvent(TS3EventType type, BaseEvent event) {
System.out.println(type.name());
}
@Override
public boolean init(String arg0) {
System.out.println("Test");
return true;
}
}
我的PluginLoader:
public static void load(File jarFile) throws InstantiationException, IllegalAccessException, ClassNotFoundException,
IOException, PluginLoadException {
String path = "";
JarFile jar = new JarFile(jarFile);
JarEntry entry = jar.getJarEntry("plugin.ini");
InputStream input = jar.getInputStream(entry);
Ini ini = new Ini(input);
if (!ini.containsKey("Plugin")) {
jar.close();
throw new PluginLoadException("Ini file not compatible.");
}
Section sec = ini.get("Plugin");
if (sec.containsKey("main")) {
path = sec.get("main");
}
ClassLoader loader = URLClassLoader.newInstance(new URL[] { jarFile.toURI().toURL() });
SprummlPlugin plugin = (SprummlPlugin) loader.loadClass(path).newInstance();
pluginslist.add(plugin);
plugin.init(Vars.VERSION);
jar.close();
}
TestPlugin的类路径是正确的
答案 0 :(得分:0)
我如何解决这个问题:
我已将this.getClass().getClassLoader()
添加到URLClassLoader.newInstance(...);