0

我像这样成功编译了一个类:

zookeeper@zookeeper-virtual-machine:~/zookeeper-3.4.5$ javac -cp "zookeeper-3.4.5.jar" org/zookeeper/Worker.java

但是当我尝试运行它时,Java 的类加载器找不到该类:

zookeeper@zookeeper-virtual-machine:~/zookeeper-3.4.5$ java -cp "zookeeper-3.4.5.jar" org.zookeeper.Worker
Exception in thread "main" java.lang.NoClassDefFoundError: org/zookeeper/Worker
Caused by: java.lang.ClassNotFoundException: org.zookeeper.Worker
    at java.net.URLClassLoader$1.run(URLClassLoader.java:217)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:321)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
Could not find the main class: org.zookeeper.Worker. Program will exit.

以下是 Worker.java 的相关部分

package org.zookeeper;
...

class Worker implements Watcher {

...

    public static void main(String[] args) throws Exception {
        Worker worker = new Worker(args[0], args[1],args[2]);
        worker.processRequest();
    }

为什么类加载器不能加载类?

4

2 回答 2

2

指定标志时-cp,当前目录不会自动在类路径中使用,因此需要显式添加:

java -cp zookeeper-3.4.5.jar:. org.zookeeper.Worker
于 2013-11-13T21:48:21.507 回答
0

为什么要引用罐子呢?

无论如何,您仍然需要路径上的类,例如,

java -cp .:zookeeper-3.4.5.jar org.zookeeper.Worker
于 2013-11-13T21:49:18.000 回答