what is the best practice to create a .jar file from a java project??
Some points to consider:
- Create proper MANIFEST.MF, which should contain:
- Build date;
- Author;
- Implementation-version;
- Use a script/program - like an Ant task - which takes care of properly creating a manifest file.
Here's a simple ant file which builds a java project, adapted from the Ant tutorial:
<project>
<target name="clean">
<delete dir="build"/>
</target>
<target name="compile">
<mkdir dir="build/classes"/>
<javac srcdir="src" destdir="build/classes"/>
</target>
<target name="jar">
<mkdir dir="build/jar"/>
<jar destfile="build/jar/HelloWorld.jar" basedir="build/classes">
<manifest>
<attribute name="Implementation-Version" value="1.0"/>
</manifest>
</jar>
</target>
<target name="run">
<java jar="build/jar/HelloWorld.jar" fork="true"/>
</target>
</project>
Read up on the basics of Sun's JAR format at this tutorial. In my opinion you should learn the basics -- namely MANIFESTs, the SDK tools -- before jumping into third party tools such as the following.
The Jar command line tool distributed with the Sun JDK:
jar -cf myjar.jar base_src_folder
Where base_src_folder
is the parent directory holding your source code.
Alternatively you could use a build tool such as Apache Ant. It has features such as the JAR target to do this for you.
Ant is not quite easy to begin with. Instead, I would suggest using an IDE, for instance NetBeans, which creates an Ant script under the hood. All you have to do is to hit "build", and you get a .jar file as result.
Apache Maven, for projects which are dependent on other projects.
Admittedly, Maven may be overkill for learning projects, but it is invaluable for larger, distributed ones.
Eclipse IDE is the best way for new comers. Just select the project right click export File, select jar anf filename.
I'm a relative novice (though not newcomber) to java but I will say that for me this thread is missing the mark for jar "Best Practices". It's relatively pedantic to simply "create a jar". The questions I have around best practices are:
1) Is it OK to have numerous versions of a particular class in a jar file? My local utilities tend to consume numerous other local utilities ("set A"). Which, in turn, consume other utilities - some of which consume other "set A" utilities. I end up with duplicate entries in the jar.
2) Is there a particularly good use for "Implementation-Version"? E.g., is that what should be used to provide the --version for an app? If so, is there a good (or any way), perhaps using annotations (?) that allow the jar file version to be displayed from the app?
3) In order to minimize the number of classes I need in the batch wrapper (script that starts the jar), I unjar other jar libraries (e.g., apache commons CLI, etc) and include it in the object jar. Is this frowned on?
Thanks for any suggestions!
- Andy