给脚找不到异常的Ant脚本 - 为什么?

时间:2012-12-17 13:01:23

标签: java ant task classnotfoundexception dir

<project name="MyProject" default="run" basedir=".">
    <description>
        simple example build file
    </description>
  <!-- set global properties for this build -->
  <property name="src" location="./src"/>
  <property name="build" location="./build"/>
  <property name="lib" location="./lib"/>
  <property name="zmq.dir" location="/usr/local/share/java"/>

  <path id="classpath.compile">
      <fileset dir="${lib}">
          <include name="**/*.jar"/>
      </fileset>
      <pathelement location="${zmq.dir}/zmq.jar"/>
  </path>

  <path id="classpath.run">
     <path refid="classpath.compile"/>
      <fileset dir="${build}/classes">
          <include name="**/*.class"/>
      </fileset>
  </path>

  <target name="clean"
        description="clean up" >
    <delete dir="${build}"/>
  </target>

  <target name="init" depends="clean">
    <!-- Create the build directory structure used by compile -->
    <mkdir dir="${build}"/>
    <mkdir dir="${build}/classes"/> 
  </target>

  <target name="compile" depends="init"
        description="compile the source " >
    <property name="compile.classpath" refid="classpath.compile"/>
    <echo message="Compiling with classpath ${compile.classpath}"/>
    <javac srcdir="${src}" 
           destdir="${build}/classes">
        <classpath refid="classpath.compile"/>
    </javac>
  </target>

  <target name="run" depends="compile">
    <property name="run.classpath" refid="classpath.run"/>
    <echo message="Running with classpath ${run.classpath}"/>
    <java fork="true"
          dir="${build}/classes"
          classname="jgf.EMDR_Client"
          classpathref="classpath.run"/>
  </target>
</project>

当我运行项目时,会给出java.lang.ClassNotFoundException: jgf.EMDR_Client

我回显编译的类路径并运行

编译是:

/Users/JGF/Projects/emdr/lib/json_simple-1.1.jar:/usr/local/share/java/zmq.jar

运行是:

/Users/JGF/Projects/emdr/lib/json_simple-1.1.jar:/usr/local/share/java/zmq.jar:/Users/JGF/Projects/emdr/build/classes/jgf/EMDR_Client.class

我的JAVA_HOME是:/Library/Java/Home

ant java dir attribute borked?

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:3)

你应该使用classpath标签,虽然路径也应该工作恕我直言。但要正确使用它。 不要直接将类添加到路径中,而只添加jar或目录:

<path id="classpath.run">
  <path refid="classpath.compile"/>
  <pathelement location="${build}/classes" />
</path>

这应该给你一条路:

/Users/JGF/Projects/emdr/lib/json_simple-1.1.jar:/usr/local/share/java/zmq.jar:/Users/JGF/Projects/emdr/build/classes
然后,Java将首先查看jar,然后查看目录/Users/JGF/Projects/emdr/build/classes

要查找类jgf.EMDR_Client,Java将在名为EMDR_Client.class的子目录中查找名为jgf的文件。所以它现在应该找到你的班级。

再说一次:Classpath元素不是类文件,而是目录或JAR文件(压缩目录)