Search code examples
javaantbuildconstantsbuild.xml

Define constants before init in ant/netbeans


I have a webapp to be ran on Tomcat6/JbossAS 5 and, for versioning purposes, I have several AND targets that will perform a set of operations to define a constant with version number and build datetime.

The targets perform the following:

  1. Delete the Release.java
  2. Copy the Release.template to Release.java with the versioning info properly set as a constant (public static final String)

The thing is that, the constant references are replaced on the code before compilation. For instance, where I have

log.debug("Release: " + Release.info);

I can see, using java decompiler, the following (let's assume that "TO_BE_DEFINED" is the initial value for Relase.info):

log.debug("Release: TO_BE_DEFINED");

The targets are the following:

<target name="build-config" >
    <!-- config -->
    <property name="project.name" value="MY PROJECT" />
    <property name="release.prefix" value="MPROJECT" />
    <property name="release.num" value="1.0" />
    <property name="release.info.file.path" value="org/my/project/Release" />
    <tstamp>
        <format property="release.date" pattern="yyyy-MM-dd HH:mm:ss z" />
    </tstamp>
    <!-- end config -->
    <property name="release.version" value="${release.prefix}-${release.num}" />
    <property name="release.info" value="${release.version} ${release.date}" />
</target>
<target name="build-replace">
    <filter token="release.info" value="${release.version} ${release.date}" />
    <delete file="${src.dir}/${release.info.file.path}.java" />
    <copy file="${src.dir}/${release.info.file.path}.template" tofile="${src.dir}/${release.info.file.path}.java" filtering="true" />
</target>

<target name="build-myproj-1.0.jar" depends="init,buil-config,build-replace,compile">
    <mkdir dir="${dist.dir}"/>
    <jar compress="true" jarfile="${dist.dir}/MPROJECT-1.0.jar">
        <fileset dir="${build.classes.dir}"
               excludes="META-INF/*.*, WEB-INF/classes/*.xml"
               includes="**/*.class"
        />
        <manifest>
            <section name="${project.name}">
                <attribute name="Release-Version" value="${release.version}" />
                <attribute name="Release-Date" value="${release.date}" />
            </section>
        </manifest>
    </jar>
</target>

and my class is defined as

public abstract class Release {

/** Release info */
public static final String INFO = "TO_BE_DEFINED";
}

I understand that this may be a little bit confusing and if I'm missing some information please feel free to ask


Solution

  • Compile-time constants are replaced in client code when the client code is compiled.

    To get the client code to pick up the new value of the constant, either recompile everything, replace the field with a getter, or use one of the strategies from this question