在我的项目中还有两个类:TheProblem和Server。
public class TheProblem {
public static void main (String args []) throws ClassNotFoundException {
ClassLoader.getSystemClassLoader().loadClass("Server");
}
}
当我从命令行执行代码时,一切正常。 但是当我使用ANT执行代码时,我得到了一个ClassNotFoundException - 虽然Server.class和TheProblem.class都位于同一目录中。
我的项目的目录结构非常简单 - 我将在此处尝试说明:
root_folder/
- build.xml
- src/
- TheProblem.java
- Server.java
- build/
- TheProblem.class
- Server.class
以下是我的build.xml文件的摘录:
<?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" />
</path>
<target name="init" >
<mkdir dir="build" />
</target>
<target name="compile" depends="init" >
<javac classpathref="project.class.path" srcdir="src" destdir="build"
includeAntRuntime="false" />
</target>
<target name="execute-problem" depends="compile">
<java classpathref="project.class.path" classname="TheProblem" />
</target>
<target name="clean" depends="init">
<delete dir="build" />
</target>
</project>
当我执行 ant compile 时,所有内容都会编译,但是当我执行 ant execute-problem 时,ClassLoader无法找到Server类并抛出ClassNotFoundException。 当我导航到构建目录并调用 java TheProblem 时,它工作得很好。我真的不知道为什么它不能使用ANT。
非常感谢你花时间阅读这篇文章。
答案 0 :(得分:1)
而不是
<target name="execute-problem" depends="compile">
<java classpathref="project.class.path" classname="TheProblem" />
</target>
尝试使用此
<target name="execute-problem" depends="compile">
<java fork="true" dir="." classname="TheProblem">
<classpath>
<path refid="project.class.path" />
</classpath>
</java>
</target>