Skip to main content

can't load .class files from jar file

No replies
mort32
Offline
Joined: 2009-06-16

I am trying to load a class file from a jar file using this code:

public class MyClassLoader extends URLClassLoader {
private URL url;

public MyClassLoader(URL url) {
super(new URL[] { url });
this.url = url;
}

public static void main(String[] args){
Class cl = null;
String jarFile = "c:/test/mytest.jar";
File f = new File(jarFile);

if(!f.exists()){
try {
throw new IOException("jar file not found!");
} catch (IOException e) {
e.printStackTrace();
}
}

URL tempURL = null;
try {
String urlPath = "file://" + jarFile + "!/";
tempURL = new URL(urlPath);
} catch (MalformedURLException e) {
e.printStackTrace();
}

MyClassLoader loader = new MyClassLoader(tempURL);
try {
cl = loader.loadClass("testpackage.Mytest");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}

}

}

the mytest.jar file contains the class file 'MyTest' in the package 'testpackage' but I keep getting the exception:

java.lang.ClassNotFoundException: testpackage.Mytest

any ideas?