I picked up instructions (and code) here and there on creating and using a class from a jar file.
I created a Test.java file :
package a;
public class Test {
public String print(){
return "TestLALALA";
}
}
And created a jar file with :
jar cvf0 Test.jar Test.java
When I extract the jar (through command-line), the class is intact.
I put the jar in a "libs" folder in my Eclipse project. I can see it in the project "Build Path" under "Libraries".
The following code hits a ClassNotFoundException :
URL[] urls = new URL[1];
try {
File file = new File("C:\\Eclipse\\Demo\\libs\\Test.jar");
urls[0] = file.toURI().toURL();
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
URLClassLoader loader = new URLClassLoader (urls);
Class classToLoad = null;
if(loader!=null)
{
try {
classToLoad = loader.loadClass("a.Test");
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
}
What did I miss ?
Thank you!
It looks like you are adding only the uncompiled .java file to the JAR rather than the compiled .class file.
Also the file within the JAR should be a/Test.class
so you need to make sure that the a
directory is present in there to represent the package path. Currently it appears that the file exists in the root of the JAR rather than within a subdirectory.