我正在开发一个 eclipse 插件,它将以编程方式运行 Ant XML 文件。
我用了org.apache.tools.ant.helper.ProjectHelperImpl
和 org.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 definitions
和 test 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/