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
[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 and
, or
, not
combine multiple conditions to archive the needs.
Of course the examples won’t work with Java 7.
Can you tell me why you think this example would not work with Java 7 ? I tested it works.
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