cxan_96 cxan_96 - 1 year ago 52
Java Question

ANT - Java ClassLoader cant find class

in my project there are - among others - two classes: TheProblem and Server.

public class TheProblem {
public static void main (String args []) throws ClassNotFoundException {

When I execute the code from the command line, everything works just fine.
But when I use ANT to execute the code, I get a ClassNotFoundException - although both Server.class and TheProblem.class are inside of the same directory.

The directory structure of my project is fairly simple - I will try to illustrate it here:

- build.xml
- src/
- build/
- TheProblem.class
- Server.class

Here is an excerpt of my build.xml file:

<?xml version="1.0" encoding="UTF-8" ?>

<project name="JAXB" default="compile">

<path id="project.class.path">
<pathelement path="${java.class.path}" />
<pathelement location="build" />

<target name="init" >
<mkdir dir="build" />

<target name="compile" depends="init" >
<javac classpathref="project.class.path" srcdir="src" destdir="build"
includeAntRuntime="false" />

<target name="execute-problem" depends="compile">
<java classpathref="project.class.path" classname="TheProblem" />

<target name="clean" depends="init">
<delete dir="build" />

When I execute ant compile, everything compiles, but when I execute ant execute-problem, the ClassLoader cannot find the Server class and throws a ClassNotFoundException.
When I navigate into the build directory and call java TheProblem, it works just fine. I really have no clue, why it doesn't work using ANT.

Thank you very much for taking the time to read this post.

Answer Source

Instead of

<target name="execute-problem" depends="compile">
         <java classpathref="project.class.path" classname="TheProblem" />

try to use this

 <target name="execute-problem" depends="compile">
   <java fork="true" dir="." classname="TheProblem">
      <path refid="project.class.path" />
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download