2014-11-01 56 views
1
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(); 
    } 

我在loadClass中收到ClassNotFoundExceptionURLClassloader无法从动态加载罐子类

我已经尝试了代码的几个变种,如

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

但所有的结果为ClassNotFoundException

我曾尝试在Eclipse中进行调试,但类加载器实例无法从jar中加载类。类Vector是空的。

+0

'myJar'是什么类型? – Henry 2014-11-01 07:42:49

+0

@Henry:java.io.File。也试过JarFile。 – javaCurious 2014-11-01 10:17:33

回答

1

成功使用的URLClassLoader的不同costructor。

0

该类是url中目录的直接子项,因此不需要包装。

试试这个没有包。就像这样:

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

另外,尝试这样的:从

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

解决方案:ClassNotFoundException while loading a class from file with URLClassLoader

+0

不幸运!我尝试了所有的排列 – javaCurious 2014-11-01 10:10:24

+0

任何人都已成功地从jar中动态加载类? – javaCurious 2014-11-02 11:56:50

+0

阅读此:http://tutorials.jenkov.com/java-reflection/dynamic-class-loading-reloading.html – viniciussss 2014-11-02 22:38:42