Call a Jar Library from Own Jar Project?
I wrote an application with java and convert it to execute jar file, my project is depend on "jxl.jar". Is there any way to copy "jxl.jar" to my jar file and after that call it.
I thin开发者_如何学编程k that called "Nested Jars" ?!?
Thanks a lot
Best Regards,
Mike
The simplest way is to unpack jxl.jar
and pack it into single jar together with your class files.
You can also put jxl.jar
into your jar, load it using JarClassLoader
and call using reflection, but it's probably not worth the effort and added complication.
This should look something like this:
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
public class Preloader
{
public static void main(String[] args) throws Exception
{
Class<Preloader> c= Preloader.class;
URLClassLoader loader = new URLClassLoader(new URL[]{
c.getResource("program.jar"),
c.getResource("library.jar")});
Class<?> main_class=loader.loadClass("Main");
Method main_method = main_class.getMethod("main", args.getClass());
main_method.invoke(null, new Object[]{args});
}
}
Unfortunately it doesn't really work with nested jars. URLClassLoader
has problems with them. You can extract your nested jars to temporary files and pass them to URLClassLoader. You can also use custom URLStreamHandler
as described here, it may even be a working solution.
You can't nest jars. But you may put the jxl.jar next to your jar, and add this jar as a classpath entry in the manifest of your jar:
Class-Path: jxl.jar
Read http://download.oracle.com/javase/tutorial/deployment/jar/downman.html for details.
If your project doesn't use multiple versions of the same library, you can do as Banthar told, extract the lib jar in your jar file and then repack everything.
Since jar files are zip files, you can use your favorite file compressing software, and copy the classes from the jxl.jar to yours. You can use the jar command too:
Extract the contents of the jxl.jar with
jar xf jxl.jar
Copy the contents to your output directory (alongside your project's compiled classes). Repack everything:
jar cf my.jar my-build-directory
Yet another option is to use jarjar. Besides embedding one jar into another, jarjar will let you have multiple versions of the same library (in different name spaces). You can use it with Ant or from the CLI.
精彩评论