loading class at runtime in java ClassNotFoundException

人盡茶涼 提交于 2019-12-02 14:22:59

问题


I am having problems calling classes at run time in java Im basically making a plugin framework

it starts off by opening plugin/Plugins.cfg and parses the test into a map.. EX text in cfg file 1 = myplugin 2 = plugin2

(each plugins main class is: plugin.(plugin name).main.class)

as you can see it loads each value from the map and trys to run its main class

public static void loadPlugins()
{
    int x = hackers.core.startup.InitializeGame.map.size();
    for (int i = 1; i<=x;i++)
    {
        String className = hackers.core.startup.InitializeGame.map.get(i + "");

        File file  = new File(System.getProperty("user.dir") + File.separator + "plugins" + File.separator + className);
        URL url = null;
        try {
            url = file.toURI().toURL();
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }  
        URL[] urls = new URL[]{url};
        ClassLoader cl = new URLClassLoader(urls);

        try {
            Class cls = cl.loadClass("plugin." + className + ".main");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        System.out.println(className);
    }
}

Class cls = cl.loadClass("plugin." + className + ".main");

^line gives me the error: java.lang.ClassNotFoundException: plugin.myplugin.main

anyone know whats wrong here?, or any suggestions, I have looked at an API for it but it was confusing to me and lacks documentation.


回答1:


Your file doesn't point to a valid class or jar file.

Debug the following line; you will notice it's path isn't an existing path in your file system.

File file  = new File(System.getProperty("user.dir") + File.separator + "plugins" + File.separator + className);

I would assume that you've forgotten to include .class in the className.



来源:https://stackoverflow.com/questions/12718965/loading-class-at-runtime-in-java-classnotfoundexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!