在运行时在java ClassNotFoundException中加载类

时间:2021-05-27 19:38:12

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

我在运行时在java中调用类时遇到问题我基本上是在创建一个插件框架

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

它首先打开插件/ Plugins.cfg,然后将测试解析成一个地图.. cfg文件中的EX文本1 = myplugin 2 = plugin2

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

(每个插件的主要类是:插件。(插件名称).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

^ line给我错误: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.

任何人都知道这里有什么问题吗?或者任何建议,我已经看过它的API,但它让我感到困惑,缺乏文档。

1 个解决方案

#1


0  

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

您的文件未指向有效的类或jar文件。

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.

我假设您忘记在className中包含.class。

#1


0  

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

您的文件未指向有效的类或jar文件。

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.

我假设您忘记在className中包含.class。