Search code examples
ant

How to conditionally specify a compiler argument in the javac task


I'm trying to write a target like so

<!-- Properties that must be set when invoking via antcall:
        DestinationDir  Directory to compile classes to.
        ReleaseVer      Java version this is being compiled for (i.e. 8, 9, etc). Must be at least 8.
        Debug           Whether to compile with debug information. Either 'on' or 'off'.
    -->
    <target name="java-support-compile" description="compile JavaSupport source">
        <mkdir dir="${DestinationDir}"/>
        <condition property="ModulesSupported">
            <not>
                <equals arg1="${ReleaseVer}" arg2="8" />
            </not>
        </condition>
        <!-- Compile GSSUtilWrapper separately, since we can't use the 'release' option when referencing the sun.security.jgss.GSSUtil package,
             and we need to add an &#45;&#45;add-exports option to access the java.security.jgss module for ${ReleaseVer} > 9 -->
        <javac srcdir="${javasupport.src.dir}" source="1.${ReleaseVer}" target="1.${ReleaseVer}" debug="${Debug}" destdir="${DestinationDir}">
            <include name="${GSSUtilWrapperFile}"/>
            <compilerarg if="${ModulesSupported}" line="--add-exports java.security.jgss/sun.security.jgss=ALL-UNNAMED" />
        </javac>
        <javac srcdir="${javasupport.src.dir}" release="${ReleaseVer}" debug="${Debug}" destdir="${DestinationDir}">
            <exclude name="${GSSUtilWrapperFile}"/>
        </javac>
    </target>

The error I'm getting is compilerarg doesn't support the "if" attribute. I need it to be conditional as if I pass in ReleaseVer=8, I get the error error: option --add-exports not allowed with target 8

I got that syntax from http://ant-contrib.sourceforge.net/compilerarg.html, but I didn't realize this wasn't in core ant (and I don't want to install anything else if possible).

How can I do this in standard ant?


Solution

  • One option, perhaps not the cleanest, would be to modify your <condition> task to set the text of the compiler arg, rather than a boolean, and use that. Something like this:

    <condition property="javac_arg"
               value="--add-exports java.security.jgss/sun.security.jgss=ALL-UNNAMED"
               else="">
      <not>
        <equals arg1="${ReleaseVer}" arg2="8" />
      </not>
    </condition>
    
    <javac compiler="modern" srcdir="." includeantruntime="no">
      <compilerarg line="${javac_arg}" />
    </javac>
    

    Note the else parameter, which ensures the arg passed to javac is empty when the condition is false.