从自定义任务中调用Ant目标会导致“无法创建任务或类型导入”错误

时间:2010-09-14 11:33:35

标签: java ant

我根据之前的posts创建了一个自定义Ant任务,该任务调用另一个xml文件中的现有目标。

在调用我想要的构建xml方面似乎正在做我想做的事情,但是,它现在抛出了一个非常奇怪的错误:

build.xml:4: Problem: failed to create task or type import
Cause: The name is undefined.
Action: Check the spelling.
Action: Check that any custom tasks/types have been declared.
Action: Check that any <presetdef>/<macrodef> declarations have taken place.
    at org.apache.tools.ant.ProjectHelper.addLocationToBuildException(ProjectHelper.java:508)
    at org.apache.tools.ant.taskdefs.Ant.execute(Ant.java:369)
    at org.hardhat.task.HardHatTask.executeHardHat(HardHatTask.java:47)
    at org.hardhat.task.HardHatTask.execute(HardHatTask.java:23)
    at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:288)
    at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)

我的自定义Ant任务正在调用的构建xml看起来像这样:

<project name="myproject" default="all" basedir=".">
    <import file="includes.xml"/>

    <target name="all" depends="doStuff" />
</project>

错误说问题与第4行和任务'import'有关。关于为什么Ant似乎不理解它自己的任务之一的任何想法?

1 个答案:

答案 0 :(得分:0)

有趣的是,它看起来不起作用的原因是因为我的自定义Ant任务看起来像这样:

public void execute() {
    Ant ant = new Ant();
    Project project = new Project();
    project.setProperty("...", ...);
    ant.setProject(project);
    File directory = new File("...");
    ant.setDir(directory);
    ant.setAntfile("build.xml");
    ant.setTarget("all");
    ant.execute();
}

我所要做的就是调用getProject()而不是新的Project(),问题就消失了:

public void execute() {
    Ant ant = new Ant();
    Project project = getProject();
    project.setProperty("...", ...);
    ant.setProject(project);
    File directory = new File("...");
    ant.setDir(directory);
    ant.setAntfile("build.xml");
    ant.setTarget("all");
    ant.execute();
}