有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用ANT根据包名动态生成JAR文件

我当前的构建文件有以下重复任务:

<jar jarfile="${build.lib}/${prefix}-foo.jar">
    <fileset dir="${build.classes}">
        <include name="com/a/c/foo/**"/>
    </fileset>  
</jar>
<jar jarfile="${build.lib}/${prefix}-bar.jar">
    <fileset dir="${build.classes}">
        <include name="com/a/c/bar/**"/>
    </fileset>
</jar>

。。。等等。问题是构建。必须为每个新包或每个新子项目修改xml。这是我工作的地方经常发生的事

我想用基于“根”包动态生成JAR及其文件名的逻辑来代替它。例如,我可以将根包设置为com/a/c,该包下的所有包都会有自己的JAR。请注意,“foo”或“bar”下的所有包都只是“foo.jar”或“bar.jar”的一部分

我为ANT查找循环逻辑任务。我在ant contrib和JWare/AntXtras中都找到了一个,但这两个都无法按预期工作


共 (2) 个答案

  1. # 1 楼答案

    这个怎么样:

    <project name="dynjar" default="jar" basedir=".">
        <property name="build.classes" value="${basedir}/classes"/>
        <property name="build.lib" value="${basedir}/lib"/>
        <property name="prefix" value="prefix"/>
        <property name="root" value="com/a/c"/>
    
        <target name="jar">
            <!  ${ant.file} is the name of the current build file  >
            <subant genericantfile="${ant.file}" target="do-jar">
    
                <!  Pass the needed properties to the subant call. You could also use
                     the inheritall attribute on the subant element above to pass all
                     properties.  >
                <propertyset>
                    <propertyref name="build.classes"/>
                    <propertyref name="build.lib"/>
                    <propertyref name="prefix"/>
                    <propertyref name="root"/>
                </propertyset>
    
                <!  subant will call the "do-jar" target for every directory in the
                     ${build.classes}/${root} directory, making the subdirectory the
                     basedir.  >
                <dirset dir="${build.classes}/${root}" includes="*"/>
            </subant>
        </target>
    
        <target name="do-jar">
            <!  Get the basename of the basedir (foo, bar, etc.)  >
            <basename file="${basedir}" property="suffix"/>
    
            <jar jarfile="${build.lib}/${prefix}-${suffix}.jar">
                <fileset dir="${build.classes}">
                    <include name="${root}/${suffix}/**"/>
                </fileset>
            </jar>
        </target>
    </project>
    
  2. # 2 楼答案

    我不知道如何循环查找所有包名,但可以使用宏来避免代码重复

    我还没试过,但可以用

    <macrodef name="build_jar">
        <attribute name="name"/>
        <sequential>
            <jar jarfile="${build.lib}/${prefix}-@{name}.jar">
                <fileset dir="${build.classes}">
                    <include name="com/a/c/@{name}/**"/>
                </fileset>
            </jar>
        </sequential
    </macrodef>
    
    <target name="build_foo">
        <build_jar name="foo"/>
    </target>
    
    <target name="build_bar">
        <build_jar name="bar"/>
    </target>