bernie2436
bernie2436

Reputation: 23901

Issue with Java class loader

I compile a class successfully like this:

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

But when I then try to run it Java's class loader can't find the class:

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.

Here are the relevant parts of 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();
    }

Why can't the class loader load the class?

Upvotes: 0

Views: 102

Answers (2)

Reimeus
Reimeus

Reputation: 159754

When the -cp flag is specified, the current directory is not automatically used in the classpath so needs to be added explicitly:

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

Upvotes: 2

Dave Newton
Dave Newton

Reputation: 160171

Why quote the jar anyway?

In any case, you still need your classes on the classpath, e.g.,

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

Upvotes: 0

Related Questions