Reputation: 795
For years I have been using an IDE (Eclipse) to compile my jar files for me, through the years I have learned about how they work however I still don't fully understand how the jar knows where the main method is, I am also curious about how simple (or not) it is to compile one manually.
I have a (sort of) IDE I'm working on that will need to be able to compile and run a jar that includes both the file from the user and either a jar or a bunch of other classes (the API), I have seen some questions here mentioning Java JavaCompiler
class but never giving demo code and there seems to be a next to no one that knows how to compile manually so I would like to contribute. So, how can I create a jar file using java code? Please provide demo code.
Upvotes: 1
Views: 290
Reputation: 1503280
I still don't fully understand how the jar knows where the main method is
That's the job of the manifest file.
I am also curious about how simple (or not) it is to compile one manually.
It's pretty straightforward - you use the jar
tool after you've built the class files.
Let's do a full walk through.
Create a directory called src
and a directory called bin
. Under src
, create a directory demo
and a file called Test.java
in that directory:
package demo;
public class Test {
public static void main(String[] args) {
System.out.println("Working!");
}
}
Now compile the code:
javac -d bin src/demo/Test.java
(That will work on both Unix and Windows.)
Then create a manifest file called manifest.txt
- it doesn't matter where it goes really, but I'll just keep it in src
for the moment:
Main-Class: demo.Test
Now build a jar file:
jar cfm test.jar src\manifest.txt -C bin demo/Test.class
And run it:
java -jar test.jar
These days you can specify the entry point on the command line instead of building a manifest file yourself:
jar cfe test.jar demo.Test -C bin demo/Test.class
See the linked docs for more details on how to use the jar
tool, and the potential contents of the manifest.
Upvotes: 4