问题描述
我正在尝试使用urlclassloader遇到麻烦。 我专门在运行时遇到ClassNotFoundException,我想知道问题是否出在我要加载的jar文件使用的文件路径上。
我正在尝试完全遵循此tutorial,并且我假设它可以正常工作,因此唯一的错误必须是我正在使用的文件路径。
C:\xxxx\xxxx\IdeaProjects\TesterforURL\src\com\jcg
我用来找到它的代码行是:
URL[] classLoaderUrls = new URL[]{new URL("file://C:/xxx/xxxx//IdeaProjects/TesterforURL/src/com/jcg/classloader.jar")};
package com.jcg;
public class Bean {
public void sayHello() {
System.out.println("Hello from loaded Bean class !!!");
}
}
这是我项目中的完整代码:
package com.jcg;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.urlclassloader;
public class urlclassloaderTest {
public static void main(String[] args) throws Exception {
// Getting the jar URL which contains target class
URL[] classLoaderUrls = new URL[]{new URL("file://C:/xxxx/xxxx//IdeaProjects/TesterforURL/src/com/jcg/classloader.jar")};
// Create a new urlclassloader
urlclassloader urlclassloader = new urlclassloader(classLoaderUrls);
// Load the target class
Class<?> beanClass = urlclassloader.loadClass("com.jcg.Bean");
// Create a new instance from the loaded class
Constructor<?> constructor = beanClass.getConstructor();
Object beanObj = constructor.newInstance();
// Getting a method from the loaded class and invoke it
Method method = beanClass.getmethod("sayHello");
method.invoke(beanObj);
}
}
在此先谢谢您的歉意,如果格式或摘要不正确,这是我的第一个问题:)
解决方法
别担心我已经对它进行了排序,它必须采用以下格式
文件:C:\ xxx \ URLUsingThingy \ src \ com \ jcg \ examples \ URLExample.jar