简体   繁体   English

URLClassLOader无法从jar动态加载类

[英]URLClassLOader unable to load classes from jar dynamically

   URLClassLoader child;
   try {
       child = new URLClassLoader(new URL[]{myJar.toURI().toURL()}, Test2.class.getClassLoader());
       child.loadClass("com.bla.bla.StringUtilService");
   } catch (MalformedURLException | ClassNotFoundException ex) {
       ex.printStackTrace();
   }

I am getting ClassNotFoundException in loadClass . 我在loadClass得到ClassNotFoundException

I have tried several variants of the code such as 我尝试了几种代码变体,例如

URL[] urls = { new URL("jar:file:" + "E:\\Works\\Workspace\\JUnit_Proj\\client.jar"+"!/") };
URLClassLoader cl = URLClassLoader.newInstance(urls);

But all results into ClassNotFoundException ! 但是所有结果都变成ClassNotFoundException

I have tried debugging in Eclipse, but the class loader instance is unable to load classes from the jar. 我已经尝试在Eclipse中调试,但是类加载器实例无法从jar中加载类。 The classes Vector is empty. Vector类为空。

Succeeded using different costructor of URLClassLoader. 使用URLClassLoader的其他构造函数成功。



    try {
        File jarFile = new File("D:\\Workspace\\Test\\Test.jar");
        URLClassLoader loader = new URLClassLoader(new URL[]{jarFile.toURI().toURL()});

        Class.forName("com.bla.bla.HelloWorld", true, loader);
        System.out.println("Success");
        loader.close();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

The class is a direct child of the dir in the url, so you need no package. 该类是url中dir的直接子类,因此不需要包。

Try this without the package. 尝试不带包装的包装。 Like this: 像这样:

URLClassLoader child;
try {
    child = new URLClassLoader(new URL[]{myJar.toURI().toURL()}, Test2.class.getClassLoader());
    child.loadClass("StringUtilService");
} catch (MalformedURLException | ClassNotFoundException ex) {
    ex.printStackTrace();
}

Also, try like this: 另外,尝试这样:

URLClassLoader child;
try {
    child = new URLClassLoader(new URL[]{myJar.toURI().toURL()}, getClass().class.getClassLoader());
    child.loadClass("StringUtilService");
} catch (MalformedURLException | ClassNotFoundException ex) {
    ex.printStackTrace();
}

Solution from: ClassNotFoundException while loading a class from file with URLClassLoader 解决方案来自: ClassNotFoundException,同时使用URLClassLoader从文件加载类

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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