javabuildant

Can't to access Main class during run target


I'm trying to build and run a Java project using Ant. The project structure looks like this:

.
├── build.xml
├── lib
│   ├── hamcrest-3.0.jar
│   └── junit-4.13.2.jar
├── src
│   └── tdd
│       ├── Board.java
│       ├── Main.java
│       ├── Player.java
│       └── TicTacToe.java
└── test
    └── tdd
        └── TicTacToeTest.java

This is my build.xml file:

<project name="TDD" default="jar" basedir=".">
    <!-- Set global properties for the build -->
    <property name="src.dir" value="src"/>
    <property name="build.dir" value="build"/>
    <property name="classes.dir" value="${build.dir}/classes"/>
    <property name="lib.dir" value="lib"/>
    <property name="dist.dir" value="${build.dir}/dist"/>
    <property name="jar.file" value="${dist.dir}/MyJavaProject.jar"/>
    <property name="test.dir" value="test"/>
    <property name="test.report.dir" value="${build.dir}/test-reports"/>

    <!-- Initialize the build directory structure -->
    <target name="init">
        <mkdir dir="${classes.dir}"/>
        <mkdir dir="${dist.dir}"/>
        <mkdir dir="${test.report.dir}"/>
    </target>

    <!-- Compile the Java source files -->
    <target name="compile" depends="init">
        <javac srcdir="${src.dir}" destdir="${classes.dir}" includeantruntime="false">
            <classpath>
                <fileset dir="${lib.dir}" includes="*.jar"/>
            </classpath>
        </javac>
    </target>

    <!-- other targets... -->

    <!-- Clean up build files -->
    <target name="clean">
        <delete dir="${build.dir}"/>
    </target>
</project>

After running ant compile the following folder is added:

.
├── build
│   ├── classes
│   │   └── tdd
│   │       ├── Board.class
│   │       ├── Main.class
│   │       ├── Player.class
│   │       └── TicTacToe.class
│   ├── dist
│   └── test-reports
.
. // the rest of the project
.

I am trying to run the Main.class using this target:

<target name="run" depends="compile">
    <java classname="tdd.Main" fork="true" />
</target>

But the tdd.Main can't be founded for some reason. How can I fix it?

More info that might help:

  1. I'm using Ant version 1.10.15
  2. My Java version is 17.0.12
  3. The Main.java class is located in the tdd package.

Solution

  • You need to set the classpath, ant is effectively scripting; that is, the <compile> task just defines a thing it can do, it does not define a global truth (that all class files are to be found in ${classes.dir}.

    <java classname="tdd.Main" fork="true">
      <classpath>
        <fileset dir="${lib.dir}" includes="*.jar"/>
        <pathelement path="${classes.dir}"/>
      </classpath>
    </java>