使用类加载器AntClassLoader []找不到ant taskdef类

时间:2013-08-31 10:21:28

标签: java xml eclipse ant eclipse-plugin

我正在开发一个以编程方式运行Ant XML文件的eclipse插件 我使用org.apache.tools.ant.helper.ProjectHelperImplorg.apache.tools.ant.Project然后解析Ant XML文件并运行特定目标,在本例中为test

我的Ant XML文件如下所示:

<!-- project class path -->
<path id="projectClassPath">
    <fileset dir="${basedir}/jars">
        <include name="**/*.jar" />
    </fileset>
</path>

<!-- task definitions -->
<taskdef file="${basedir}/tasks.properties">
    <classpath refid="projectClassPath" />
</taskdef>

<!-- test custom ant task -->
<target name="test" description="test target">
    <customTask />
</target>

<!-- test echo -->
<target name="testEcho" description="test echo target">
    <echo message="this is a test."/>
</target>

tasks.properties文件如下所示:

customTask=my.custom.task.CustomTask

我以编程方式运行Ant文件的java代码:

Project ant = new Project();
ProjectHelperImpl helper = new ProjectHelperImpl();
MyDefaultLogger log = new MyDefaultLogger();

ant.init();
helper.parse(ant, antXml);

log.setMessageOutputLevel(Project.MSG_VERBOSE);
ant.addBuildListener(log);
ant.executeTarget(testTarget);

手动运行目标test 正常,但以编程方式运行test目标会显示错误

taskdef class my.custom.task.CustomTask cannot be found using the classloader AntClassLoader[]

如果我在没有project class pathtask definitionstest custom ant task的情况下以编程方式执行文件,它将成功运行。

我的假设是,当以编程方式运行Ant文件时,它没有以某种方式注册类路径?
编辑:
多个目标名称test已将<!-- test echo -->目标名称更改为testEcho。 (信用:@smooth雷鬼)

1 个答案:

答案 0 :(得分:1)

我已经设法修复了我的错误,我改变了调用Ant XML文件的Java实现,它就像魅力一样。
我的Java代码如下所示:

// get the default custom classpath from the preferences
AntCorePreferences corePreferences = AntCorePlugin.getPlugin().getPreferences();
URL[] urls = corePreferences.getURLs();

// get the location of the plugin jar
File bundleFile = FileLocator.getBundleFile(myPlugin.getBundle());
URL url = bundleFile.toURI().toURL();

// bond urls to complete classpath
List<URL> classpath = new ArrayList<URL>();
classpath.addAll(Arrays.asList(urls));
classpath.add(url);

AntRunner runner = new AntRunner();
// set custom classpath
runner.setCustomClasspath(classpath.toArray(new URL[classpath.size()]));
// set build file location
runner.setBuildFileLocation(xmlFile.getAbsolutePath());
// set build logger
runner.addBuildLogger(MyDefaultLogger.class.getName());
// set the specific target to be executed
runner.setExecutionTargets(new String[] { "test" });
// run
runner.run();