在运行时在java ClassNotFoundException中加载类 [英] loading class at runtime in java ClassNotFoundException

查看:337
本文介绍了在运行时在java ClassNotFoundException中加载类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

(每个插件主要class是:plugin。(插件名称).main.class)

(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给出错误:java.lang.ClassNotFoundException:plugin.myplugin.main

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

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

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.

推荐答案

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

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

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

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

这篇关于在运行时在java ClassNotFoundException中加载类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆