Java类加载器的问题

时间:2013-11-13 21:45:07

标签: java

我成功编译了一个类:

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();
    }

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

2 个答案:

答案 0 :(得分:2)

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

java -cp zookeeper-3.4.5.jar:. org.zookeeper.Worker

答案 1 :(得分:0)

为什么要引用jar呢?

在任何情况下,你仍然需要在类路径上你的类,例如,

java -cp .:zookeeper-3.4.5.jar org.zookeeper.Worker