mtfurlan
mtfurlan

Reputation: 1062

Create java library with Ant

I'm trying to put some classes in a jar, for use as a library.

For this test, I'm trying to have one class, apiInterface, and it's in the package project.api.

I got here thinking I was using the library wrong, as I was getting "Package project.api does not exist" at the import line, but This answer implies that the output of jar tf project.jar should be

project/api/apiInterface.class

while I get

apiInterface.class
apiInterface.java

The java file being included is intended, but is not necessary.

The relevant part of my build.xm

<target name="buildAPI" depends="compile">                  
    <mkdir dir="${jar}" />                                  
    <jar destfile="${jar}/${ant.project.name}-api.jar">  
        <fileset dir="${bin}/${ant.project.name}/api"/> 
        <fileset dir="${src}/${ant.project.name}/api"/>
    </jar>                                                  
</target>

compile successfully compiles the java and puts the .class file in bin/project/api.

Upvotes: 1

Views: 470

Answers (1)

M A
M A

Reputation: 72854

The Jar file will contain the list of files under the directory specified in the fileset elements. Since you specify the directory as ${bin}/${ant.project.name}/api, the task will simply search under this directory and include the class file in the Jar, i.e. ${bin}/${ant.project.name}/api/apiInterface.class.

To also include the directories corresponding to the package, simply change the dir attribute to point to the root folder, in this case ${bin}. Same for the source files.

<jar destfile="${jar}/${ant.project.name}-api.jar">  
    <fileset dir="${bin}"/> 
    <fileset dir="${src}"/>
</jar>

If only this package should be included (i.e. other packages should not be in the Jar), use the includes attribute:

<jar destfile="${jar}/${ant.project.name}-api.jar">  
    <fileset dir="${bin}" includes="${ant.project.name}/api/*.class" /> 
    <fileset dir="${src}" includes="${ant.project.name}/api/*.java" /> 
</jar>

You can check this link from the Ant manual for how to properly use this task.

Upvotes: 1

Related Questions