Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bundling JAR dependencies with executable JAR (Über JAR) from command line

I'm trying to create an executable jar from the command line. The main class in the JAR has dependencies that i have packaged into another plain JAR file.

I want to package the dependency JAR together with the executable JAR in order to have a single JAR file to ship.

What i have tried so far is the following:

The dependency Hello.class file has the mock code:

public class Hello {
    public String getHello() {
        return "Well hello there!!";
    }
}

I have packaged class file into hello.jar using:

jar cvfM hello.jar Hello.class

The hello.jar content is now:

hello.jar -+- Hello.class

Now i have the main class with the mock code:

public class Main {
    public static void main(String[] args) {
        System.out.println(new Hello().getHello());
    }
}

I then create a manifest file manifest.txt with the following content:

Main-Class: Main
Class-Path: hello.jar

I now create the executable JAR using:

jar cvfm main.jar manifest.txt Main.class hello.jar

The main.jar content is now:

main.jar -+- Main.class
          |
          +- hello.jar
          |
          +- META-INF -+- MANIFEST.MF

Running the executable JAR using:

java -jar main.jar

I get a class loader error for the Hello class dependency. I understand that this is because the class loader looks for hello.jar in the same path as main.jar. So when i put a copy of hello.jar alongside main.jar i am able to run it.

What do i need to do in order to be able to run main.jar with hello.jar inside of it?

I know that you will ask: "why is he trying to do it this way?". I know that ppl mostly use Eclipse, Ant, Maven or other tools to do this. But please just humor me :)

like image 700
onlyteo Avatar asked Jul 25 '11 14:07

onlyteo


1 Answers

Your approach is completely wrong unfortunately. There is no "normal" way to place a jar inside of another jar. So your hello.jar has nothing to do inside of main.jar! The point is the "normal" classloader wont look for jar files inside of jars, hence you get the class not found error. However: if you want desparetly to do that, then google for "OneJar" and go to http://one-jar.sourceforge.net/

like image 161
Angel O'Sphere Avatar answered Sep 30 '22 00:09

Angel O'Sphere