Can't load classes from dir. with jars while can do loading classes when jars unzipped/unpacked
community! Would be great if u could help me w/ my issue.
I got a custom class loader which is gonna to be java.system.class.loader
- it holds
urls where to find classes. Like this:
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);
}
}
}
Then I run the java(JDK6) with -Djava.system.class.loader=TestSystemClassLoader eg.TestMain, where eg.TestMain' main:
public static void main(String[] args) throws Exception {
// here I got system CL which is what I want.
ClassLoader cl = Thread.c开发者_如何转开发urrentThread().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);
}
The thing which makes me mad is that if I unpack/unzip/unjar the junit-4.8.2.jar - then eg.TestMain would work!
The question is - how to tell java(JDK6) that I want whole directory to be in classpath, i.e. any file residing in the directory.
Thanks in advance!
Find all the jars and add them:
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);
}
}
精彩评论