Classpath for taskdef?
Asked Answered
P

2

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?

Peralta answered 22/12, 2010 at 16:12 Comment(0)
M
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>
Moeller answered 22/12, 2010 at 16:33 Comment(0)
B
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.

Bysshe answered 22/12, 2010 at 16:26 Comment(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.Bysshe
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.Ylangylang

© 2022 - 2024 — McMap. All rights reserved.