java - ant 中的类路径验证

标签 java ant build-process build classpath

我有一个 <path id="...">在我的 build.xml .在调用编译器之前,我想验证类路径上的每个 jar/目录是否存在,并打印一条缺少的警告。有人知道现有的解决方案吗?或者我需要为此编写自己的任务吗?


好的,我决定去做一个自定义任务。在这里,以防万一有人需要这样的东西:

import java.io.File;
import java.util.Iterator;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.types.Reference;
import org.apache.tools.ant.types.ResourceCollection;
import org.apache.tools.ant.types.resources.Resources;

public class CheckClasspathTask extends Task {

    private Reference reference;

    public CheckClasspathTask() {
    }

    public void setRefId(Reference reference) {
        this.reference = reference;
    }

    public void execute() throws BuildException {
        Resources resources = new Resources();
        resources.setProject(getProject());
        resources.add((ResourceCollection) reference.getReferencedObject());
        boolean isFirst = true;
        for (Iterator i = resources.iterator(); i.hasNext(); ) {
            String f = i.next().toString();
            if (!new File(f).exists()) {
                if (isFirst) {
                    isFirst = false;
                    System.out.println("WARNING: The following entries on your classpath do not exist:");
                }
                System.out.println(f);
            }
        }
    }
}

最佳答案

这将检查类路径中的每个文件或文件夹是否存在。如果其中之一不存在,它将导致构建失败并显示第一个找不到的名称。

<target name="check-classpath" depends="create-classpath">
    <pathconvert pathsep="," property="myclasspath" refid="compile.classpath"/>
    <foreach list="${myclasspath}" param="file" target="check-file-or-folder-exists" />
</target>

<target name="check-file-or-folder-exists">
    <fail message="Error: ${file} not found">
      <condition>
        <not>
          <available file="${file}" />
        </not>
      </condition>
    </fail>
</target>

请注意 <foreach>在 ant-contribs -- Ant Contribs clickable LINK

这将需要加载 ant-contrib jar 并连接其中的所有目标:

<taskdef resource="net/sf/antcontrib/antcontrib.properties">
    <classpath>
        <pathelement location="${some.lib.dir}/ant-contrib-1.0b3.jar" />
    </classpath>
</taskdef>

应该存在一个<for>任务将允许设置一个选项以继续遍历所有路径元素并且只在最后显示错误。我发现我的 Eclipse 版本有 <foreach>已经在类路径中,所以我认为这对我来说已经足够了。

关于java - ant 中的类路径验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/751501/

相关文章:

java - 如何为证书固定预先确定 OkHTTP sha1 哈希?

java.lang.LinkageError : loader constraint violation: when resolving method "com. sun.tools.javac.api.JavacTool.getTask

c# - 在 Visual Studio 中为 C# 项目管理多个配置文件

java - 创建由 Maven 项目构建的 Artifact 列表

performance - 如何在多模块项目中计时(分析)maven目标

java - 什么是引用复制技术以及为什么字符串对象引用值不会更改?

java - Eclipse - Java - Gradle 正在跳过 jacocoTestReport

java - 如何更改在项目中创建文件的文件夹?

linux - ANT 执行失败 : java. io.IOException : Cannot run program "cp ": java. io.IOException : error=2, 没有这样的文件或目录

java - 通过检查 junit 报告导致 ant 构建失败?