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

标签 java xml eclipse ant eclipse-plugin

我正在开发一个 eclipse 插件,它将以编程方式运行 Ant XML 文件。
我用了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 target 以编程方式显示此错误:

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

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

我的假设是,当以编程方式运行 Ant 文件时,它没有以某种方式注册类路径?

编辑:
多个目标名称 test已更改 <!-- test echo -->目标名称为 testEcho . (致谢:@smooth reggae)

最佳答案

我已经设法修复了我的错误,我更改了调用 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();

关于java - 使用类加载器 AntClassLoader[] 找不到 ant taskdef 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18547053/

相关文章:

html - xsl 为每个节点创建折叠/展开面板

javascript - Eclipse - 使用 require.js define(...) 支持大纲 View

java - 编译我的代码时找不到符号

java - 在其他函数中而不是 OnCreate() 方法中初始化按钮

java - 如何使用java替换无效字符

android - R.java 不存在……但它确实存在!安装 ADT 10.0.0 后开始出现问题

eclipse - 未找到 Java 虚拟机 (Eclipse)

java - 用于描述在不首先实例化对象的情况下为对象赋值的术语是什么?

java - 在需要很长时间的函数之前和之后显示来自 ActionListener 的消息

xml - XPath 中运算符的优先级是什么?