Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ant include external .jar

I want to include external jar to my java project. I'm using ant. External .jar is in folder lib. My build.xml looks something like that:

<?xml version="1.0" encoding="UTF-8"?>
<project>
    <path id="classpath">
        <fileset dir="lib" includes="**/*.jar"/>
    </path>

    <target name="clean">
        <delete dir="build"/>
    </target>

    <target name="compile">
        <mkdir dir="build"/>
        <javac srcdir="src" destdir="build" classpathref="classpath" />
    </target>

    <target name="jar">
        <mkdir dir="trash"/>
        <jar destfile="trash/test.jar" basedir="build">
            <zipgroupfileset dir="lib" includes="**/*.jar"/>
            <manifest>
                <attribute name="Main-Class" value="com.Test"/>
            </manifest>
        </jar>
    </target>

    <target name="run">
        <java jar="trash/test.jar" fork="true"/>
    </target>
</project>

But it doesn't work. When I want to import something from the external .jar, there is an error after command ant compile: package com.something does not exist.. What should I edit to get it working?

Exact error:

  Compiling 23 source files to xy/build
  xy/src/com/Test.java:5: package com.thoughtworks.xstream does not exist
  import com.thoughtworks.xstream.*;
  ^
  1 error
like image 1000
Pajushka Avatar asked Apr 15 '12 18:04

Pajushka


2 Answers

You should try without the includes attribute:

<fileset dir="lib" />

And in the jar part you include the classes like this:

<zipgroupfileset includes="*.jar" dir="lib"/>
like image 133
gulyan Avatar answered Nov 16 '22 16:11

gulyan


You can't put external libraries into a jar and expect the classloader to use those jars. Unfortunately this is not supported.

There are ant tasks like one jar that help you, to create a jar file, that contains everything you need.

This bit is from the background information of one jar:

Unfortunately this is does not work. The Java Launcher$AppClassLoader does not know how to load classes from a Jar inside a Jar with this kind of Class-Path. Trying to use jar:file:jarname.jar!/commons-logging.jar also leads down a dead-end. This approach will only work if you install (i.e. scatter) the supporting Jar files into the directory where the jarname.jar file is installed.

Another approach is to unpack all dependent Jar files and repack them inside the jarname.jar file. This approach tends to be fragile and slow, and can suffer from duplicate resource issues.

Other Alternative:

  • jarjar: Jar Jar Links is a utility that makes it easy to repackage Java libraries and embed them into your own distribution
like image 38
oers Avatar answered Nov 16 '22 15:11

oers