1<section xmlns="http://docbook.org/ns/docbook" 2 xmlns:xlink="http://www.w3.org/1999/xlink" 3 xml:id="sec-language-java"> 4 5<title>Java</title> 6 7<para>Ant-based Java packages are typically built from source as follows: 8 9<programlisting> 10stdenv.mkDerivation { 11 name = "..."; 12 src = fetchurl { ... }; 13 14 buildInputs = [ jdk ant ]; 15 16 buildPhase = "ant"; 17} 18</programlisting> 19 20Note that <varname>jdk</varname> is an alias for the OpenJDK.</para> 21 22<para>JAR files that are intended to be used by other packages should 23be installed in <filename>$out/share/java</filename>. The OpenJDK has 24a stdenv setup hook that adds any JARs in the 25<filename>share/java</filename> directories of the build inputs to the 26<envar>CLASSPATH</envar> environment variable. For instance, if the 27package <literal>libfoo</literal> installs a JAR named 28<filename>foo.jar</filename> in its <filename>share/java</filename> 29directory, and another package declares the attribute 30 31<programlisting> 32buildInputs = [ jdk libfoo ]; 33</programlisting> 34 35then <envar>CLASSPATH</envar> will be set to 36<filename>/nix/store/...-libfoo/share/java/foo.jar</filename>.</para> 37 38<para>Private JARs 39should be installed in a location like 40<filename>$out/share/<replaceable>package-name</replaceable></filename>.</para> 41 42<para>If your Java package provides a program, you need to generate a 43wrapper script to run it using the OpenJRE. You can use 44<literal>makeWrapper</literal> for this: 45 46<programlisting> 47buildInputs = [ makeWrapper ]; 48 49installPhase = 50 '' 51 mkdir -p $out/bin 52 makeWrapper ${jre}/bin/java $out/bin/foo \ 53 --add-flags "-cp $out/share/java/foo.jar org.foo.Main" 54 ''; 55</programlisting> 56 57Note the use of <literal>jre</literal>, which is the part of the 58OpenJDK package that contains the Java Runtime Environment. By using 59<literal>${jre}/bin/java</literal> instead of 60<literal>${jdk}/bin/java</literal>, you prevent your package from 61depending on the JDK at runtime.</para> 62 63<para>It is possible to use a different Java compiler than 64<command>javac</command> from the OpenJDK. For instance, to use the 65Eclipse Java Compiler: 66 67<programlisting> 68buildInputs = [ jre ant ecj ]; 69</programlisting> 70 71(Note that here you don’t need the full JDK as an input, but just the 72JRE.) The ECJ has a stdenv setup hook that sets some environment 73variables to cause Ant to use ECJ, but this doesn’t work with all Ant 74files. Similarly, you can use the GNU Java Compiler: 75 76<programlisting> 77buildInputs = [ gcj ant ]; 78</programlisting> 79 80Here, Ant will automatically use <command>gij</command> (the GNU Java 81Runtime) instead of the OpenJRE.</para> 82 83</section> 84