2011-09-20 57 views
0

社区!如果你能帮我解决我的问题,那会很棒。无法从dir加载类。有罐子的时候可以做罐装类解压缩/拆包罐子

我得到了一个自定义的类加载器,这将是java.system.class.loader - 它拥有 网址在哪里可以找到类。就像这样:

public class TestSystemClassLoader extends URLClassLoader { 

    public TestSystemClassLoader(ClassLoader parent) { 
    super(classpath(), parent); 
    } 

    private static URL[] classpath() { 
    try { 
     // I got junit-4.8.2.jar under this url. 
     URL url = new File("D:\\Work\\lib\\junit-4\\").toURI().toURL(); 
     return new URL[] { url }; 
    } 
    catch (MalformedURLException e) { 
     throw new IllegalArgumentException(e); 
    } 
    } 
} 

然后,我-Djava.system.class.loader = TestSystemClassLoader eg.TestMain, 运行java(JDK6)其中eg.TestMain'主:

public static void main(String[] args) throws Exception { 
    // here I got system CL which is what I want. 
ClassLoader cl = Thread.currentThread().getContextClassLoader(); 
    // here I got: "Exception in thread "main" java.lang.ClassNotFoundException: org.junit.runners.JUnit4" 
Class<?> clazz = Class.forName("org.junit.runners.JUnit4", true, cl); 
} 

事情这让我很生气,如果我解压/ unzip/unjar junit-4.8.2.jar - 那么 eg.TestMain会工作!

问题是 - 如何告诉java(JDK6)我希望整个目录位于classpath中,即 即驻留在目录中的任何文件。

在此先感谢!

回答

0

找到所有的罐子,并添加他们:

private static URL[] classpath() { 
    try { 
     File file = new File("D:\\Work\\lib\\junit-4\\"); 
     List<URL> urls = new ArrayList<URL>(); 
     for (File f : file.listFiles()) { 
      if (f.isFile() && f.getName().endsWith(".jar")) { 
       urls.add(f.toURI().toURL()); 
      } 
     } 

     return urls.toArray(new URL[0]); 
    } 
    catch (MalformedURLException e) { 
     throw new IllegalArgumentException(e); 
    } 
}