我正在尝试使用 Ant 编译和运行一个项目,但我得到了 NoClassDefFoundError。这是位于 src 文件夹中的 OutlookToGmailCalendarSync.java 文件:
package sample.calendar;
public class OutlookToGmailCalendarSync {
public static void main(String[] args) {
System.out.println("hi");
}
}
这是我的 build.xml 文件:
<project name="MyCalendarSample" 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="dist" location="dist"/>
<path id="path.class">
<pathelement location="build/sample/calendar"/>
</path>
<target name="run" depends="compile"
description="Runs the complied project">
<!-- Run -->
<java fork="true" classname="OutlookToGmailCalendarSync">
<classpath>
<path refid="path.class"/>
</classpath>
</java>
</target>
<target name="compile" depends="init"
description="compile the source " >
<!-- Compile the java code from ${src} into ${build} -->
<javac srcdir="${src}" destdir="${build}"/>
</target>
<target name="init">
<!-- Create the time stamp -->
<tstamp/>
<!-- Create the build directory structure used by compile -->
<mkdir dir="${build}"/>
</target>
<target name="clean"
description="clean up" >
<!-- Delete the ${build} directory trees -->
<delete dir="${build}"/>
</target>
</project>
这是结果:
C:\java\my>ant
Buildfile: C:\java\my\build.xml
init:
compile:
[javac] C:\java\my\build.xml:30: warning: 'includeantruntime' was not set, d
efaulting to build.sysclasspath=last; set to false for repeatable builds
[javac] Compiling 1 source file to C:\java\my\build
run:
[java] java.lang.NoClassDefFoundError: OutlookToGmailCalendarSync (wrong na
me: sample/calendar/OutlookToGmailCalendarSync)
[java] at java.lang.ClassLoader.defineClass1(Native Method)
[java] at java.lang.ClassLoader.defineClass(ClassLoader.java:791)
[java] at java.security.SecureClassLoader.defineClass(SecureClassLoader
.java:142)
[java] at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
[java] at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
[java] at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
[java] at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
[java] at java.security.AccessController.doPrivileged(Native Method)
[java] at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
[java] at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
[java] at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
[java] at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
[java] at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.j
ava:482)
[java] Exception in thread "main"
[java] Java Result: 1
BUILD SUCCESSFUL
Total time: 1 second
C:\java\my>
即使在阅读了其他论坛帖子之后,我仍然不明白为什么会发生这种情况。在运行时,编译的类在 build/sample/calendar 中,这是 classpath 设置的,所以我看不到问题。