11

I am defining a new task in Ant. I exported it as a jar and added to my buildfile:

<taskdef classname="X" classpath="Y.jar"/>

The problem is that this fails at runtime. It tells me it didn't find the class. By adding the jar to the classpath, it is corrected.

My question is: Is there a way that I can refer to my jar from the Ant buildfile, without changing the classpath?

martin clayton
  • 76,436
  • 32
  • 213
  • 198
computealot
  • 111
  • 1
  • 1
  • 4

2 Answers2

11

If you know the path of your jar, inside ant script you can define the classpath for your own task.

<taskdef name="myTaskName" classname="com.myorg.myclass">
  <classpath>
    <pathelement location="pathToMyJar.jar"/>
  </classpath>
</taskdef>
guinoise
  • 304
  • 2
  • 6
1

Yes. I'm assuming that you looked at the doc for taskdef, which just shows the task name and implementing class. However, taskdef subclasses typedef, and if you look at the doc for the latter you'll see that there's also a classpath attribute.

HOWEVER, using this attribute means that your ant scripts are tied to a particular environment; they aren't very portable. A far better approach is to pass the classpath into Ant, using the -lib invocation option.

Anon
  • 2,654
  • 16
  • 10
  • 2
    And if you're using a `CLASSPATH` environment variable, don't. Delete it from your environment setup, and get into the habit of specifying classpaths explicitly. Because otherwise, you'll find yourself with a hard-to-debug problem where a library gets loaded from your classpath and you don't expect it. Or someone else can't run your code because s/he doesn't have the same `CLASSPATH` environment variable. – Anon Dec 22 '10 at 16:27
  • 3
    I don't see why this is _a far better approach_. Specifying the classpaths with the `-lib` option just makes the user aware of those paths. You still need to tell the user where to look for them (for instance, in a readme, help file or an echoed message). Or you can decide to restructure your project directory hierarchy to include those libs in a specific subdir, becoming "environment-independent." A build script should take care of these details and ideally produce a sensible object with the default `ant` invocation. – Alberto Mar 21 '12 at 14:58