【问题标题】:Can't load classes from dir. with jars while can do loading classes when jars unzipped/unpacked无法从目录加载类。 with jars while 可以在 jars 解压/解压时加载类
【发布时间】:2011-11-20 19:18:32
【问题描述】:

社区!如果你能帮助我解决我的问题,那就太好了。

我有一个自定义类加载器,它将是 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' main:

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

让我生气的是,如果我解压/解压缩/解压 junit-4.8.2.jar - 那么 eg.TestMain 会工作!

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

提前致谢!

【问题讨论】:

    标签: classloader urlclassloader dynamic-class-loaders


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2013-10-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-14
      • 1970-01-01
      相关资源
      最近更新 更多