Java Task

## Java

### Description

Executes a Java class within the running (Apache Ant) JVM or forks another JVM if specified.

If odd things go wrong when you run this task, set fork=true to use a new JVM.

Since Ant 1.6.3, you can interact with a forked JVM, as well as sending input to it via the input and inputstring attributes.

#### Running Ant as a background process on Unix(-like) systems

If you run Ant as a background process (like `ant &`) and use the `<java>` task with spawn set to false and fork to true, you must provide explicit input to the forked process or Ant will be suspended because it tries to read from the standard input.

### Parameters

Attribute | Description | Required
--- | --- | ---
classname | the Java class to execute. | Exactly one of the four
jar | the location of the jar file to execute (must have a `Main-Class` entry in the manifest). fork must be set to true if this option is selected. See notes below for more details.
module | The initial or main module to resolve (must have a `Main-Class` entry in the manifest). fork must be set to true if this option is selected. since Ant 1.9.7
sourcefile | The location of a ".java" file or a file containing shebang with Java source code. Set this attribute to run Java single file source programs, a feature introduced in Java 11. fork must be set to true if this option is selected. since Ant 1.10.5
args | the arguments for the class that is executed. Deprecated, use nested `<arg>` elements instead. | No
classpath | the classpath to use. | No
classpathref | the classpath to use, given as reference to a `Path` defined elsewhere. | No
modulepath | Specify where to find application modules. A list of directories of modules, module files or exploded modules. since Ant 1.9.7 | No
modulepathref | The modulepath to use, given as reference to a `Path` defined elsewhere. since Ant 1.9.7 | No
fork | if enabled triggers the class execution in another JVM. | No; default is false
spawn | if enabled allows to start a process which will outlive Ant. Requires that fork is true, and not compatible with timeout, input, output, error, result attributes | No; default is false
jvm | the command used to invoke JVM. The command is resolved by `java.lang.Runtime.exec()`. Ignored if fork is false. | No, default is `java`
jvmargs | the arguments to pass to the forked JVM, ignored if fork is disabled. Deprecated, use nested `<jvmarg>` elements instead. | No
maxmemory | Max amount of memory to allocate to the forked JVM, ignored if fork is false | No
failonerror | Stop the build process if the command exits with a return code other than 0. | No; default is false (see note)
resultproperty | The name of a property in which the return code of the command should be stored. Only of interest if failonerror is false and if fork is true. | No
dir | The directory to invoke the JVM in, ignored if fork is false. | No
output | Name of a file to which to write the output. If the error stream is not also redirected to a file or property, it will appear in this output. | No
error | The file to which the standard error of the command should be redirected. | No
logError | This attribute is used when you wish to see error output in Ant's log and you are redirecting output to a file/property. The error output will not be included in the output file/property. If you redirect error with the error or errorProperty attributes, this will have no effect. | No
append | Whether output and error files should be appended to or overwritten. | No; defaults to false
outputproperty | The name of a property in which the output of the command should be stored. Unless the error stream is redirected to a separate file or stream, this property will include the error output. | No
errorproperty | The name of a property in which the standard error of the command should be stored. | No
input | A file from which the executed command's standard input is taken. This attribute is mutually exclusive with the inputstring attribute | No; default is to take standard input from console unless spawn is true
inputstring | A string which serves as the input stream for the executed command. This attribute is mutually exclusive with the input attribute. | No; default is to take standard input from console unless spawn is true)
newenvironment | Do not propagate old environment when new environment variables are specified. | No; default is false, ignored if fork is false
timeout | Stop the command if it doesn't finish within the specified time (given in milliseconds). It is highly recommended to use this feature only if fork is true. | No
clonevm | If set to true, then all system properties and the bootclasspath of the forked JVM will be the same as those of the JVM running Ant. since Ant 1.7 | No; default is false, ignored if fork is false

### Parameters specified as nested elements

#### arg and jvmarg

Use nested `<arg>` and `<jvmarg>` elements to specify arguments for the Java class and the forked JVM respectively. See Command line arguments.

#### sysproperty

Use nested `<sysproperty>` elements to specify system properties required by the class. These properties will be made available to JVM during the execution of the class (either Ant's JVM or the forked JVM). The attributes for this element are the same as for environment variables.

#### syspropertyset

Since Ant 1.6.

You can specify a set of properties to be used as system properties with syspropertysets.

#### classpath

`Java`'s classpath attribute is a path-like structure and can also be set via a nested `classpath` element.

#### bootclasspath

Since Ant 1.6.

The location of bootstrap class files can be specified using this path-like structure—will be ignored if fork is not true or the target JVM doesn't support it (i.e. Java 1.1).

#### env

It is possible to specify environment variables to pass to the forked JVM via nested `env` elements. See the description in the section about exec

Settings will be ignored if fork is false.

#### permissions

Since Ant 1.6.

Security permissions can be revoked and granted during the execution of the class via a nested `permissions` element. For more information please see permissions.

When the permission `RuntimePermission exitVM` has not been granted (or has been revoked) the `System.exit()` call will be intercepted and treated like indicated in failonerror.

Note:
If you do not specify permissions, a set of default permissions will be added to your Java invocation to make sure that the Ant run will continue or terminated as indicated by failonerror. All permissions not granted per default will be checked by whatever security manager was already in place. `exitVM` will be disallowed.

Settings will be ignored if fork is true.

#### assertions

Since Ant 1.6.

You can control enablement of Java 1.4 assertions with an `<assertions>` subelement.

Assertion statements are currently ignored in non-forked mode.

#### redirector

Since Ant 1.6.2

A nested I/O Redirector can be specified. In general, the attributes of the redirector behave as the corresponding attributes available at the task level. The most notable peculiarity stems from the retention of the `<java>` attributes for backwards compatibility. Any file mapping is done using a `null` sourcefile; therefore not all Mapper types will return results. When no results are returned, redirection specifications will fall back to the task level attributes. In practice this means that defaults can be specified for input, output, and error output files.

### Errors and return codes

By default, the return code of a `<java>` is ignored. Alternatively, you can set resultproperty to the name of a property and have it assigned to the result code (barring immutability, of course). When you set failonerror=true, the only possible value for resultproperty is 0. Any non-zero response is treated as an error and would mean the build exits.

Similarly, if failonerror=false and fork=false, then `<java>` must return 0 otherwise the build will exit, as the class was run by the build JVM.

#### modulepath

Since Ant 1.9.7

`Java`'s modulepath attribute is a path-like structure and can also be set via a nested `modulepath` element.

#### upgrademodulepath

Since Ant 1.9.7

The location of modules that replace upgradeable modules in the runtime image can be specified using this path-like structure.

### JAR file execution

The parameter of the jar attribute is of type `File`; that is, the parameter is resolved to an absolute file relative to the base directory of the project, not the directory in which the Java task is run. If you need to locate a JAR file relative to the directory the task will be run in, you need to explicitly create the full path to the JAR file.

When using the jar attribute, all classpath settings are ignored according to Oracle's specification.

### Examples

Run a class in this JVM with a new jar on the classpath

    <java classname="test.Main">
      <arg value="-h"/>
      <classpath>
        <pathelement location="dist/test.jar"/>
        <pathelement path="${java.class.path}"/>
      </classpath>
    </java>

Run the JAR `test.jar` in this project's `dist/lib` directory, using the manifest supplied entry point, forking (as required), and with a maximum memory of 128 MB. Any non zero return code breaks the build.

    <java jar="dist/test.jar"
          fork="true"
          failonerror="true"
          maxmemory="128m">
      <arg value="-h"/>
      <classpath>
        <pathelement location="dist/test.jar"/>
        <pathelement path="${java.class.path}"/>
      </classpath>
    </java>

Run the JAR `dist/test.jar` relative to the directory `${exec.dir}`, this being the same directory in which JVM is to start up.

    <java dir="${exec.dir}"
          jar="${exec.dir}/dist/test.jar"
          fork="true"
          failonerror="true"
          maxmemory="128m">
      <arg value="-h"/>
      <classpath>
        <pathelement location="dist/test.jar"/>
        <pathelement path="${java.class.path}"/>
      </classpath>
    </java>

Run a given class with the current classpath.

    <java classname="test.Main"/>

Add system properties and JVM properties to JVM as in `java -Xrunhprof:cpu=samples,file=log.txt,depth=3 -DDEBUG=true test.Main`

    <java classname="test.Main"
          fork="yes" >
      <sysproperty key="DEBUG" value="true"/>
      <arg value="-h"/>
      <jvmarg value="-Xrunhprof:cpu=samples,file=log.txt,depth=3"/>
    </java>

Use a given Java implementation (other than the one Ant is currently using) to run the class. For documentation in the log taskname is used to change the [java] log-prefix to [java1.4].

    <java classname="ShowJavaVersion" classpath="."
          jvm="path-to-java14-home/bin/java" fork="true"
          taskname="java1.4"/>

Note: you can not specify the (highly deprecated) MS JVM, `jview.exe`, as jvm, since it takes different parameters than other JVMs. That JVM can be started from `<exec>` if required.

Run the module `TestModule` resolved on the modulepath `lib/:dist/test.jar` with a maximum memory of 128 MB. Any non zero return code breaks the build.

    <java fork="true"
          failonerror="true"
          maxmemory="128m"
          module="TestModule"
          modulepath="lib:dist/test.jar"/>

Run the class `Main` in module `TestModule` resolved on the modulepath `lib/:dist/test.jar` with a maximum memory of 128 MB. Any non zero return code breaks the build.

    <java fork="true"
          failonerror="true"
          maxmemory="128m"
          module="TestModule"
          classname="Main">
      <modulepath>
        <pathelement location="lib"/>
        <pathelement location="dist/test.jar"/>
      </modulepath>
    </java>