views:

1211

answers:

2

I am trying to access the class files packaged as a library but unfortunately the jar libraries should be packaged in another jar file.

As an example say I have a.jar that contains some class libraries. I can call (import) the classes in the jar file from my external java application. Now I need to put this a.jar inside another jar say b.jar and need to access (import) the classes in a.jar from outside of the b.jar.

This is not the thing I want to do :)

+3  A: 

You would have to write a classloader which was able to deal with "jars within jars." This sounds like a pretty bad idea to me.

Don't merge the jar files - just have them separately on disk. I realise you may need to persuade management of the necessity of having more files, but it really is going to make everything a lot simpler. Writing a classloader is non-trivial...

Jon Skeet
+1 for calling "jars within jars" a bad idea.
Stephen C
A: 

Maybe I'm not understanding properly, but I believe what you want is to execute your program with the other JAR file (also) on your classpath.

So let's say you have some core in A.jar, and some library in B.jar. You could execute your program like this (replace : with ; on Windows):

java -cp A.jar:B.jar main.class.Name args

Where main.class.Name is your main class name, and args is where all of your command line arguments goes.

You can also put a Main-Class and Class-Path attribute in your manifest.mf like this:

Class-Path: B.jar
Main-Class: main.class.Name

Then you can execute the program like this:

java -jar A.jar args

To tell you the truth, I used to think that it was slick to distribute my application as a single JAR file, with all of the dependencies extracted and wrapped in a single giant JAR file. The problem is that some applications end up with quite a few dependencies, and every time I made a change to my code, it also meant that I had to distribute all of the dependent code, even though nothing in the dependencies had changed. That meant distributing gigantic JAR files, even though there might only be minor changes.

By using a Class-Path manifest attribute, I can distribute applications which can be executed in exactly the same way as a single JAR file (double-clicking on some systems, or the simple "java -jar" incantation) but save a ton of time and bandwidth by not transferring all of the duplicate libraries with subsequent software releases.

It is also possible to put any dependent JARs into their own directory (let's call it lib for now) and modify the Class-Path so that all of the JAR paths look like "lib/B.jar". Then you don't end up with your main program directory full of many tiny JAR files.

Adam Batkin
The problem is that the OP has one jar file *inside* another jar file.
Jon Skeet
I suppose that becomes more clear by re-reading the title of the question, but definitely not from the question text itself
Adam Batkin
I updates the question :)
Chathuranga Chandrasekara