How to Check Java version in Ant

Ant has built-in property ${ant.java.version}, you can directly use it to get Java or JVM version, the following example prints out Java version.

Build.xml
<target name="print-version"> 
   <echo>Java/JVM version: ${ant.java.version}</echo> 
   <echo>Java/JVM detail version: ${java.version}</echo> 
</target>

The output getting from example:

[echo] Java/JVM version: 1.5
[echo] Java/JVM detail version: 1.5.0_08

How I can Check Java/JVM version in Ant?

Ant has task condition which sets a property if a certain condition holds true, we compare current Java version to 1.5/1.6, if false then fail the build.

Filename: Build.xml
<fail message="Unsupported Java version: ${ant.java.version}. 
  Make sure that the Java version is 1.5 or greater.">
  <condition>
    <not>
      <or>
        <equals arg1="${ant.java.version}" arg2="1.5"/>
        <equals arg1="${ant.java.version}" arg2="1.6"/>
      </or>
    </not>
  </condition>
</fail>

Example 2 to check version in Ant:
We compare current Java version to 1.5/1.6 and set result back to property of condition, this property can be used later on.

<project basedir="." default="check-java-version">
  <target name="get-java-version">
    <condition property="java.version">
      <not>
        <or>
          <equals arg1="${ant.java.version}" arg2="1.5"/>
          <equals arg1="${ant.java.version}" arg2="1.6"/>
        </or>
      </not>
    </condition>
  </target>
  <target name="check-java-version" depends="get-java-version" unless="java.version">
    <fail message="Unsupported Java version: ${ant.java.version}. 
    Make sure that the Java version is 1.5 or greater."/>
  </target>
</project>

here is no “greater than” or “less than” logic, but certainly we can use Ant andornot combine multiple conditions to archive the needs.

Rate article
ASJAVA.COM
Add a comment

Your email address will not be published. Required fields are marked *

*

code

  1. Anthony Goubard

    Of course the examples won’t work with Java 7.

    Reply
    1. admin author

      Can you tell me why you think this example would not work with Java 7 ? I tested it works.

      Reply
  2. MR

    Since the property java.version is allways populated (by example with 1.5.0_08), this code will never fail with any java version, unless if is used java version less than the version supported by ant (that will throw java.lang.UnsupportedClassVersionError).

    I suggest to be used other property to check the java version (java.version.checked), and the conditions should match non supported versions (1.1, 1.2, 1.3, 1.4 for check greater or equal to java 5).
    MR

    Reply