loading class at runtime in java ClassNotFoundExce

2019-03-06 08:43发布

问题:

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.