【问题标题】:Cannot cast from child class to parent interface无法从子类转换为父接口
【发布时间】:2015-11-13 14:08:41
【问题描述】:

我正在为我的 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);

}

我的测试插件:

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;
    }

}

我的插件加载器:

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 的类路径正确

【问题讨论】:

  • SprummlPlugin 是否包含在插件的 .jar 中?
  • 不,我将 TestPlugin 导出为 Jar 文件而不是可运行的 jar 文件
  • 只要确保在任何时间类路径中只有一个SprummlPlugin
  • 我只有自己的 SprummlPlugin。 Tst Plugin 只实现它(我只是将我的 Main Jarfile 添加到 testplugin 的构建路径中)
  • 您遇到的问题已解决here

标签: java class plugins casting


【解决方案1】:

我是如何解决这个问题的:

我将this.getClass().getClassLoader()添加到我的URLClassLoader.newInstance(...);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-14
    • 1970-01-01
    • 2016-10-20
    相关资源
    最近更新 更多