简体   繁体   中英

loading class at runtime in java ClassNotFoundException

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM